您的位置:首页 > 移动开发 > Android开发

android-线程与消息处理(一)

2014-05-25 17:04 218 查看
前言:

这篇文章是在第一次学习android线程与消息处理的学习笔记,对于其中的一些理解可能会有错误

一、为什么要有线程与消息处理

因为android中activity中对ui的处理都是在主线程中进行的,也就是onCreate()方法中执行,自己写的线程中是不允许对ui进行处理的,因此产生了消息处理的机制

1、多线程的基本操作

主要有四部分:创建线程,开启线程,让线程休眠,中断线程

创建线程:

android中提供了两个创建线程的方法:通过Thread类的构造方法创建,并重写run()方法;另一种是通过Runnable接口实现

Thread类构造方法创建线程:

构造方法:Thread(Runnable runnable) 参数runnable是一个Runnable的对象

大体结构:

Thread thread = new Thread(new Runnable() {

//重写run()方法

@Override

public void run() {

// TODO Auto-generated method stub

//你要执行的操作

}

});

Runnable接口创建线程

语法格式:

public class runnable extends Activity implements Runnable() {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

public void run() {

//要执行的操作

}

};

}

线程操作的一些方法:

thread.start();启动线程

thread.sleep();睡眠线程

thread.wait();等待线程

thread.join();

thread.interrupt();中断线程

下面是使用Runnable接口实现i++的test code

package com.testhandlerandthread;

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

public class MainActivity extends Activity implements Runnable {

//定义按钮变量

Button bn1,bn2;

//声明两个成员变量

int i;

private Thread thread;

@Override

protected void onCreate(Bundle savedInstanceState) {

// TODO Auto-generated method stub

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

bn1 = (Button) findViewById(R.id.bn1);

bn2 = (Button) findViewById(R.id.bn2);

bn1.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

// TODO Auto-generated method stub

i = 0;

//为这个activity创建一个线程,用thread实例化这个线程

thread = new Thread(MainActivity.this);

//启动这个线程

thread.start();

}

});

bn2.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

// TODO Auto-generated method stub

if (thread != null){

thread.interrupt();//终止线程的方法

thread = null;//将里面的数据清空,在java中就是将栈内存中的变量与堆内存断开联系,java会自动回收走垃圾,这样数据就清空了

}

System.out.println("线程已中断");

}

});

}

@Override

public void run() {

// TODO Auto-generated method stub

//判断线程目前是否没有中断,是的话就i++,并输出当前i的值实现这个判断是采用下面循环方法中的参数的方法(调用类Thread的获取当前线程currentThread()并判断是否是中断断的方法)

while (!Thread.currentThread().isInterrupted()){

i++;

System.out.println("现在的i是多少了:"+i);

}

}

//为什么有要在onDestory()方法中调用中断线程的操作,可能是因为线程是独立于这个activity的操作,可能当这个activity销毁后,此线程不会随之销毁,所以要在activity销毁时,终止线程,多方面的考虑

@Override

protected void onDestroy() {

if (thread != null){

thread.interrupt();//中断线程的方法

thread = null;

}

//调用父类方法

super.onDestroy();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: