这里记录下项目中用到的ThreadLocal的用法
public class ThreadLocalUtil {
private final static ThreadLocal<Executor> threadLocal = new ThreadLocal<Executor>();public static Executor getExecutor() {
return threadLocal.get();
}
public static void setExecutor(Executor executor) {
threadLocal.set(executor);
}
public static void removeExecutor() {
threadLocal.remove();
}
}
public class Task implements Runnable{
private Executor executor;
public Executor getExecutor() {
return executor;
}
public void setExecutor(Executor executor) {
this.executor = executor;
}
@Override
public void run() {
// 线程开始执行保存对象到ThreadLocal
ThreadLocalUtil.setExecutor(executor);
//Task执行的后续代码,后续代码可以从通过ThreadLocalUtil.getExecutor()获取执行当前task的excecutor对象
//线程执行结束清除ThreadLocal保存的对象
ThreadLocalUtil.removeExecutor();
}
}