Override interrupt method for thread in threadpool

家住魔仙堡 提交于 2019-12-09 13:28:01

问题


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();
      }
    }

回答1:


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.



来源:https://stackoverflow.com/questions/54564377/override-interrupt-method-for-thread-in-threadpool

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!