gpt4 book ai didi

java - 我可以访问为线程池线程提交任务(并且正在运行)的线程吗?

转载 作者:行者123 更新时间:2023-11-30 05:43:48 26 4
gpt4 key购买 nike

我想重写MyThreadPoolExecutorThreadPoolExecutorprotected void beforeExecute(Thread t, Runnable r) { },我想在那里知道哪个线程提交了该线程将要运行的任务吗?我想将任务提交线程的 threadLocals 复制到将运行此任务的线程(t)(在 threadPool 中)。

最佳答案

我成功了

public class MyThreadPoolExecutor extends ThreadPoolExecutor {

public MyThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
}

@Override
public Future<?> submit(Runnable task) {
// get the threadLocal from current thread which is task submitting thread
boolean threadLocalValueFromParentThread = ThreadLocalsUtils.getThreadLocalValueForThisThread.get();

Runnable wrappedTask = () -> {
try {
// set value of task submitting thread's value in whichever thread gets this runnable.
ThreadLocalsUtils.setThreadLocalValueForThisThread(threadLocalValueFromParentThread);
task.run();
} finally {
ThreadLocalsUtils.setThreadLocalValueForThisThread(false);
}
};
return super.submit(wrappedTask);
}

}

关于java - 我可以访问为线程池线程提交任务(并且正在运行)的线程吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55188651/

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