首页 > 代码库 > Android 异步任务 代码很简短,简单异步工具封装,方便执行异步任务

Android 异步任务 代码很简短,简单异步工具封装,方便执行异步任务

比较简单,就3个类。

1、创建一个单例的线程池,用来执行异步任务

<pre name="code" class="java">package com.ferris.pool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class FerrisPoolManager {
	private ExecutorService service;

	private FerrisPoolManager() {
		int num = Runtime.getRuntime().availableProcessors();
		service = Executors.newFixedThreadPool(num * 2);
	}

	private static FerrisPoolManager manager;

	public static FerrisPoolManager getInstance() {
		if (manager == null) {
			synchronized (FerrisPoolManager.class) {
				if(manager == null) {
				manager = new FerrisPoolManager();
				}
			}
		}
		return manager;
	}

	public void addTask(Runnable runnable) {
		service.execute(runnable);
	}
	public void cancelTask(){
		service.shutdown();
	}
}



2、定义一个任务接口

package com.ferris.pool;

public interface FerrisTaskListem {
	public void get();  //运行在线程里

	public void update(); //运行在主线程(从哪里new就是哪个线程,也不一定是主线程service等)
}



3、任务执行对象

package com.ferris.pool;

import android.os.Handler;
import android.os.Message;

public class FerrisTask {
	private FerrisTaskListem taskListem;
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if(taskListem!=null){
				taskListem.update();
			}
		};
	};

	public FerrisTask(FerrisTaskListem taskListem) {
		this.taskListem = taskListem;
	}

	public void Execute(){
		FerrisPoolManager.getInstance().addTask(new RunTask());
	}
	
	public class RunTask implements Runnable {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			if(taskListem!=null){
				taskListem.get();
			}
			Message message=Message.obtain();
			handler.sendMessage(message);

		}
	}

	
}


4、使用方法


FerrisTask ferrisTask = new FerrisTask(new FerrisTaskListem() {
			@Override
			public void update() {  //主线程
				// TODO Auto-generated method stub
				String name = Thread.currentThread().getName();
				System.out.print(name);
			}

			@Override
			public void get() { //UI线程
				// TODO Auto-generated method stub
				String name = Thread.currentThread().getName();
				System.out.print(name);

			}
		});
		ferrisTask.Execute();




Android 异步任务 代码很简短,简单异步工具封装,方便执行异步任务