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

Tom*_*ica 3 java multithreading executorservice

我想确保我的类(更新程序服务)的所有方法都在 的线程内调用ExecutorService(假设甚至只有一个线程)。未给出方法的顺序,因此那些公共方法可能会从 的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);
  }
Run Code Online (Sandbox Code Playgroud)

我已经在 Swing 中做了类似的事情 - 对于像changeApplicationTrayIcon我简单地检查我是否在 GUI 线程中的方法,如果不是,我使用SwingUtilities.invokeLater.

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

Bri*_*new 5

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