本文介绍了线程池中线程的重写中断方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有这个:
class Queue {
private static ExecutorService executor = Executors.newFixedThreadPool(1);
public void use(Runnable r){
Queue.executor.execute(r);
}
}
我的问题是-如何定义池中使用的线程,特别是想覆盖池中线程的中断方法:
my question is - how can I define the thread that's used in the pool, specifically would like to override the interrupt method on thread(s) in the pool:
@Override
public void interrupt() {
synchronized(x){
isInterrupted = true;
super.interrupt();
}
}
推荐答案
通过指定 ThreadFactory
.
Executors.newFixedThreadPool(1, new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
return new Thread(r) {
@Override
public void interrupt() {
// do what you need
}
};
}
});
当然,ThreadFactory
可以用lambda表示.
Sure, a ThreadFactory
can be expressed by a lambda.
ThreadFactory factory = (Runnable r) -> new YourThreadClass(r);
如果线程不需要其他设置(例如使其成为守护程序),则可以使用方法引用.但是,构造函数YourThreadClass(Runnable)
应该存在.
If there is no additional setup needed for a thread (like making it a daemon), you can use a method reference. The constructor YourThreadClass(Runnable)
should exist, though.
ThreadFactory factory = YourThreadClass::new;
我建议您阅读 ThreadPoolExecutor
和 Executors
.他们提供了很多信息.
I'd advise reading the docs of ThreadPoolExecutor
and Executors
. They are pretty informative.
这篇关于线程池中线程的重写中断方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!