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

Detect if current thread is ExecutorService thread

我想确保我的 class(更新程序服务)的所有方法都在 ExecutorService 的线程中被调用(前提是只有一个线程)。未给出方法的顺序,因此 public 的方法可能会从 Executor 的线程和其他一些线程(主要是 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.

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

如果您提供 ThreadFactory to your implementation of an ExecutorService (e.g. a ThreadPoolExecutor) 的实现,您可以记录工厂创建的线程(通过引用或 ID)并稍后对该 ThreadFactory 执行查找以确定它们是否由工厂创建,因此是一个执行线程