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

标签 java multithreading executorservice

我想确保我的类(更新程序服务)的所有方法都在 ExecutorService 的线程中被调用(前提是只有一个线程)。未给出方法的顺序,因此可能会从 Executor 的线程和一些其他线程(主要是 GUI 线程)调用公共(public)方法。

我的代码:

  // 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 的实现对于 ExecutorService 的实现(例如 ThreadPoolExecutor ),您可以记录工厂创建的线程(通过引用或 ID)并稍后对该 ThreadFactory 执行查找以确定它们是否已由创建工厂,因此是一个执行线程

关于java - 检测当前线程是否为 ExecutorService 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34798891/

相关文章:

java - 如何在非 Activity 状态下调用电话?

java - 如何序列化 Java 类的静态数据成员?

Java String DateTime 到 toEpochMilli - 不同区域

java - 如何避免使用递归调用使 executorservice 拥塞/停滞/死锁

java - 在无限循环内调用 ExecutorService Submit()

java - 单击按钮时略有延迟

ruby - 测试缓存(多进程)和内存方法

c++ - 在多线程 C++11 程序中未处理异常时会发生什么?

c++ - 跨整个项目方法的单例类

java - 在 lambda 表达式中使用非最终循环变量