【java学习】android线程 几种对比

来源:互联网 发布:知乎上面的回复,经典 编辑:程序博客网 时间:2024/05/22 00:05

【实现Runnable接口】

步骤:

  1. 定义类实现Runnable接口
  2. 覆盖Runnable接口中的run方法
  3. 通过Thread类建立线程对象 
  4. 将Runnable接口的子类对象作为实际参数传递给Thread类的构造函数
  5. 调用Thread类的start方法开启线程并调用Runnabe接口子类的run方法
MyThread t = new MyThread();//MyThread为implements Runnable的类new Thread(t).start();

在实现Runnable接口的类中,自定义的run方法所属对象是Runnable接口的子类对象。

【继承Thread类】

实现Runnable接口相比继承Thread类有如下好处:

  1. 避免单继承的局限,一个类可以继承多个接口。
  2. 适合于资源的共享。
关于资源的共享,就像上文提及的那样,实现Runnable,线程代码存在接口的子类的run方法中。而继承Thread,线程代码存放Thread子类run方法中。

详细查看:http://www.oschina.net/question/565065_86563


【AsyncTask异步任务】

在Android中实现异步任务机制有两种方式,Handler和AsyncTask.

相较线程,AsyncTask实现更加简单。但很多时候是不可控的。建议没有大量的与主线程交互操作,使用Thread.

在实际应用中,遇到很奇怪的问题,有时候AsyncTask无法进入doInBackground中。通过参阅http://blog.csdn.net/mddy2001/article/details/17127065文章,解决了问题。要么不用AsyncTask,直接用Thread实现。要么将调用execute方法,改为调用task.executeOnExecutor(Executors.newCachedThreadPool());

原因是,execute()提交的任务,按先后顺序每次只运行一个。相当于同一时间,只有一个线程在再执行任务。而executeOnExecutor,让所有线程并发执行。

package com.luo.activity;import java.util.ArrayList;import java.util.Iterator;import java.util.List;import android.app.Activity;import android.os.AsyncTask;import android.os.Bundle;public class MainActivity extends Activity {protected List<AsyncTask<Void, Void, Integer>> mAsyncTasks = new ArrayList<AsyncTask<Void, Void, Integer>>();@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);setAsync();}public void putAsyncTask(AsyncTask<Void, Void, Integer> asyncTask) {mAsyncTasks.add(asyncTask.execute());}public void clearAsyncTask() {Iterator<AsyncTask<Void, Void, Integer>> iterator = mAsyncTasks.iterator();while (iterator.hasNext()) {AsyncTask<Void, Void, Integer> asyncTask = iterator.next();if (asyncTask != null && !asyncTask.isCancelled()) {asyncTask.cancel(true);}}mAsyncTasks.clear();}private void setAsync() {MainActivity.this.clearAsyncTask();MainActivity.this.putAsyncTask(new AsyncTask<Void, Void, Integer>() {@Overrideprotected void onPreExecute() {super.onPreExecute();}@Overrideprotected Integer doInBackground(Void... params) {return 0;}@Overrideprotected void onPostExecute(Integer result) {super.onPostExecute(result);if (result == 0) {} }});}}

使用注意:

  1)在AsyncTask中,尽量不掉用UI函数如toast。而在handler中实现。具体原因:http://blog.csdn.net/sunshinetan/article/details/52823856。

  2)耗时任务放在doInBackground中。


【handler异步任务】

  参考:http://blog.csdn.net/sunshinetan/article/details/52588373

【ExecutorService线程池】

  查看http://www.cnphp6.com/archives/61093

0 0
原创粉丝点击