java-检测当前线程是否为ExecutorService线程

我想确保在ExecutorService的线程(只要有一个线程)中调用我类的所有方法(更新程序服务).由于未给出方法的顺序,因此可能会从执行器线程和其他一些线程(主要是GUI线程)中调用那些公共的方法.

我的代码:

  // Instantiated lazy using synchronized getter - I decided not to bother with shared locks
  private ExecutorService executor;
  /**
   * Provides compatibility between calls from executor thread pool and other threads. 
   * No matter the thread from which you call this method, the callback will be executed
   * within the loop. Proper events will be raised in the loop thread as well, so
   * mind to use SwingUtilities.invokeLater if event involves GUI operations.
   * @param callback
   * @throws Exception 
   */
  protected void runInExecutorIfNeeded(Callable callback) throws Exception {
    // Already in executor thread
    if(Thread.currentThread() == /* ??? */)
      callback.call();
    // Not in executor thread, go to executor thread and call callback there
    else
      getExecutor().submit(callback);
  }

我已经在Swing中做过类似的事情-对于诸如changeApplicationTrayIcon之类的方法,我只是检查我是否在GUI线程中,否则,我使用了SwingUtilities.invokeLater.

那么,如何检查执行程序线程中当前代码是否正在运行?

解决方法:

如果为ExecutorService的实现提供了ThreadFactory的实现(例如ThreadPoolExecutor),则可以记录工厂创建的线程(通过引用或id),并在以后针对该ThreadFactory执行查找,以确定是否它们是由工厂创建的,因此是执行程序线程

上一篇:如何在Java中查找非常大的文件复制状态


下一篇:java-为什么缓存的线程池会创建两个线程,为什么关闭它会改变它呢?