java线程池threadlocal_ThreadLocal在线程池中的使用方法

论坛 期权论坛 编程之家     
选择匿名的用户   2021-5-31 06:23   74   0

import java.util.concurrent.ArrayBlockingQueue;

import java.util.concurrent.ThreadPoolExecutor;

import java.util.concurrent.TimeUnit;

public class ThreadLocalTest {

public static void main(String[] args) {

MyThreadPoolExecutor pool = new MyThreadPoolExecutor(2, 2, 10,

TimeUnit.SECONDS, new ArrayBlockingQueue(1000));

int i = 0;

while (true) {

final int loop = i++;

// 进行set的Runnable

pool.execute(new Runnable() {

@Override

public void run() {

MyThreadLocal.currentAgentId.set(1);

System.out.println(loop + "=1==" + Thread.currentThread()

+ "seted currentAgentId:"

+ MyThreadLocal.currentAgentId.get());

}

});

pool.execute(new Runnable() {

@Override

public void run() {

System.err.println(loop + "=2==" + Thread.currentThread()

+ "seted currentAgentId:"

+ MyThreadLocal.currentAgentId.get());

}

});

pool.execute(new Runnable() {

@Override

public void run() {

System.out.println(loop + "=3==" + Thread.currentThread()

+ "seted currentAgentId:"

+ MyThreadLocal.currentAgentId.get());

}

});

try {

Thread.sleep(2000);

} catch (InterruptedException e) {

e.printStackTrace();

}

System.err.println("================");

}

// pool.shutdown();

}

}

class MyThreadPoolExecutor extends ThreadPoolExecutor {

public MyThreadPoolExecutor(int i, int j, int k, TimeUnit seconds,

ArrayBlockingQueue arrayBlockingQueue) {

super(i, j, k, seconds, arrayBlockingQueue);

}

@Override

protected void beforeExecute(Thread t, Runnable r) {

//任务执行回调可以作为重置操作

MyThreadLocal.currentAgentId.set(888);

}

protected void afterExecute(Runnable r, Throwable t) {

//任务执行回调可以作为重置操作

MyThreadLocal.currentAgentId.set(null);

}

}

abstract class MyThreadLocal {

public static ThreadLocal currentAgentId = new ThreadLocal();

}

分享到:

18e900b8666ce6f233d25ec02f95ee59.png

72dd548719f0ace4d5f9bca64e1d7715.png

2012-11-12 17:51

浏览 5921

评论

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP