Say I have this:
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();
}
}
Define how threads for the pool are created by specifying a ThreadFactory
.
Executors.newFixedThreadPool(1, new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
return new Thread(r) {
@Override
public void interrupt() {
// do what you need
}
};
}
});
Sure, a ThreadFactory
can be expressed by a lambda.
ThreadFactory factory = (Runnable r) -> new YourThreadClass(r);
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;
I'd advise reading the docs of ThreadPoolExecutor
and Executors
. They are pretty informative.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With