gpt4 book ai didi

java - 如何在ThreadFactory中初始化ThreadLocal变量?

转载 作者:行者123 更新时间:2023-12-01 13:13:24 25 4
gpt4 key购买 nike

我有 n 个资源和 n 个线程,每个线程将使用一个资源来执行其任务。
创建线程时,我希望它接收资源并将其存储在本地线程变量中。
当线程完成后,我需要释放资源

ExecutorService pool = Executors.newFixedThreadPool(10, new ThreadFactory() {
public Thread newThread(final Runnable r) {
Thread thread = new Thread(new Runnable() {
public void run() {
//set ThreadLocal with a resource
//run
//close the resource
}
});
return thread;
}
});

最佳答案

根据需要重写getResource()和releaseResource()。

class MyThreadFactory implements ThreadFactory {
// String is the type of resource; change it if nesessary
static final ThreadLocal<String> currentResourceKey = new ThreadLocal<String>();

int n = 0;

String getResource() {
n++;
System.out.println("aquired:" + n);
return Integer.valueOf(n).toString();
}

void releaseResource(String res) {
System.out.println("released:" + res);
}

@Override
public Thread newThread(Runnable r) {
return new Thread(r) {
public void run() {
currentResourceKey.set(getResource());
try {
super.run();
} finally {
releaseResource(currentResourceKey.get());
}
}
};
}
}

测试代码:

    ExecutorService pool = Executors.newFixedThreadPool(2,new MyThreadFactory());
for (int k = 0; k < 5; k++) {
pool.submit(new Runnable() {
public void run() {
String res = currentResourceKey.get();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(" executed:"+res+" on "+Thread.currentThread().getName());
}
});
}
pool.shutdown();

关于java - 如何在ThreadFactory中初始化ThreadLocal变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22657019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com