public class ThreadUtil {
private static final String TAG = ThreadUtil.class.getSimpleName();
private static class HandlerHolder {
public final static Handler sInstance = new Handler(Looper.getMainLooper());
}
/**
* Posts a runnable to the UI thread.
*/
public static void postOnUiThread(Runnable runnable) {
getUiThreadHandler().post(runnable);
}
/**
* Posts a runnable to the UI thread, to be run after the specified amount of time elapses.
*/
public static void postDelayedOnUiThread(Runnable runnable, long delayMillis) {
getUiThreadHandler().postDelayed(runnable, delayMillis);
}
/**
* Gets a handler which uses the main looper.
*/
public static Handler getUiThreadHandler() {
return HandlerHolder.sInstance;
}
private static class WorkHandlerHolder {
public static Handler INSTANCE = getHandler();
private static Handler getHandler() {
HandlerThread thread = new HandlerThread("Work-thread");
thread.start();
return new Handler(thread.getLooper());
}
}
/**
* Posts a runnable to the work thread.
* <p>
* 这是一个单线程池,不适合做长耗时的操作
* <p>
* 文件读写,网络请求等长耗时的工作 请使用{@link SimpleTask} or {@link ThreadPoolManager}.
*/
public static void postOnWorkThread(Runnable runnable) {
getWorkHandler().post(runnable);
}
/**
* Posts a runnable to the work thread, to be run after the specified amount of time elapses.
* <p>
* 这是一个单线程池,不适合做长耗时的操作
* <p>
* 文件读写,网络请求等长耗时的工作 请使用{@link SimpleTask} or {@link ThreadPoolManager}.
*/
public static void postDelayedOnWorkThread(Runnable runnable, long delayMillis) {
getWorkHandler().postDelayed(runnable, delayMillis);
}
/**
* Remove any pending posts of Runnable r that are in the message queue.
*/
public static void removeCallbacksOnWorkThread(Runnable runnable) {
getWorkHandler().removeCallbacks(runnable);
}
/**
* Gets a handler which uses the work thread looper.
*/
public static Handler getWorkHandler() {
return WorkHandlerHolder.INSTANCE;
}
public static void checkAndRunOnUiThread(Runnable r) {
if (Looper.myLooper() == Looper.getMainLooper()) {
r.run();
} else {
postOnUiThread(r);
}
}
public static abstract class TraceTask implements Runnable {
private String mTraceName;
public TraceTask(String traceName) {
mTraceName = traceName;
}
/**
* 需要重写的方法
*/
public abstract void runTask();
@Override
public void run() {
Trace.beginSection(mTraceName);
runTask();
Trace.endSection();
}
}
public static void slientSleep(long millis) {
try {
Thread.sleep(millis);
} catch (Exception e) {
Log.w(TAG, "slient sleep " + e.toString());
}
}
private static Executor workExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread result = new Thread(r);
result.setName("EXECUTOR-WORK");
return result;
}
});
private static Scheduler workScheduler = Schedulers.from(workExecutor);
public static Executor getWorkExecutor() {
return workExecutor;
}
public static Scheduler getWorkScheduler() {
return workScheduler;
}
}