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

Android 创建线程执行任务

2015-09-08 15:20 435 查看
一、新建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() {
@Override
public void run() {
//在此执行具体任务
}
}, 100L); // 100L位delay执行的时间
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Android Thread