Android 创建线程执行任务

来源:互联网 发布:采购流程优化的趋势 编辑:程序博客网 时间:2024/05/21 10:09

一、新建CommonWorkingThread类,如下:

import android.os.Handler;import android.os.HandlerThread;import android.util.Log;public class CommonWorkingThread {private static HandlerThread thread = null;private static Handler handler = null;private CommonWorkingThread() {}public static class CommonWorkingThreadHolder {public static CommonWorkingThread instance = new CommonWorkingThread();}public static CommonWorkingThread getInstance() {initHandler();return CommonWorkingThreadHolder.instance;}public boolean execute(Runnable r) {if (handler != null) {Log.i("CommonWorkingThread", ">>> working thread execute ");return handler.post(r);}return false;}public boolean execute(Runnable r, long delayMillis) {if (handler != null) {Log.i("CommonWorkingThread",">>> working thread execute delayMillis " + delayMillis);return handler.postDelayed(r, delayMillis);}return false;}public Handler getHandler() {return handler;}private static void initHandler() {if (thread == null || !thread.isAlive() || thread.isInterrupted()|| thread.getState() == Thread.State.TERMINATED) {thread = new HandlerThread("tpush.working.thread");thread.start();handler = new Handler(thread.getLooper());Log.i("CommonWorkingThread", ">>> Create new working thread."+ thread.getId());}}}
二、在需要用到的地方按如下调用方式调用:

CommonWorkingThread.getInstance().execute(new Runnable() {@Overridepublic void run() {//在此执行具体任务}}, 100L); // 100L位delay执行的时间



0 0
原创粉丝点击