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

时间:2016-01-14 20:16:13

标签: 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);
  }

我已经在Swing中做了类似的事情 - 对于像changeApplicationTrayIcon这样的方法我只是检查我是否在GUI线程中,如果没有,我使用了SwingUtilities.invokeLater

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

1 个答案:

答案 0 :(得分:4)

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