多线程的常见操作

一.创建线程

在Android中,提供了两种创建线程的方法,一种是通过Thread类的构造方法创建线程,并重写run()方法,另一种是通过实现Runnable接口实现。下面分别进行介绍。

1.通过Thread类的构造方法创建线程

在Android中,可以使用Thread类提供的构造方法来创建线程

Thread(Runnable runnable);

该构造方法的参数runnable,可以通过创建一个Runnable类的对象并重写其run()方法来实现,例如要创建一个名称为thread的线程,可以使用如下代码

Thread thread = new Thread(new Runnable(){
      @Override
       public void run(){
               //要执行的操作
}
});

说明:在run()方法中,可以编写要执行的操作代码,当线程被开启时,run()方法将会被执行。

2.通过实现Runnable接口创建线程

在Android中,还可以通过实现Runnable()接口来创建线程。实现Runnable接口的语法如下:

public class ClassName extends Object implements Runnable

当一个类实现Runnable接口后,还需要实现其run()方法,在该方法中,可以编写要执行的代码,例如,要创建一个实现了Runnable接口的Activity,可以使用下面代码

<pre name="code" class="java">public class MainActivity extends Activity implements Runnable{
	@Override
	private Thread thread;
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		Button btn1 = (Button)findViewById(R.id.button1);
		Button btn2 = (Button)findViewById(R.id.button2);
		btn1.setOnClickListener(new OnClickListener){
			thread = new Thread(MainActivity.this);
			thread.start();
		}
		btn2.setOnClickListener(new OnClickListener){
			if( thread != nul ){
				thread.interrupt();   //中断线程
				thread=null;
			}
		}
	}
	@Override
	public void run(){
		//要执行的操作
	}
	
}

 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值