检测当前线程是否为ExecutorService线程 [英] Detect if current thread is ExecutorService thread

查看:118
本文介绍了检测当前线程是否为ExecutorService线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想确保我的类的所有方法(更新程序服务)都在ExecutorService的线程中调用(假设甚至只有一个线程).没有给出方法的顺序,因此可以从Executor的线程和其他一些线程(主要是GUI线程)中调用那些公共的方法.

I want to ensure all methods of my class (updater service) are called within the ExecutorService's thread (provided there's even a single thread). The order of the methods is not given so those that are public might get called from both the Executor's thread and some other threads, mostly GUI thread.

我的代码:

  // 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.

I have already done a similar thing in Swing - for methods like changeApplicationTrayIcon I simply checked if I'm in GUI thread and if not, I used SwingUtilities.invokeLater.

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

So, how do I check if current code is running in Executor's thread?

推荐答案

如果提供了

If you provide an implementation of a ThreadFactory to your implementation of an ExecutorService (e.g. a ThreadPoolExecutor), you could record the threads created by the factory (either by reference or id) and perform a lookup against that ThreadFactory later on in order to determine if they've been created by the factory, and thus an executor thread

这篇关于检测当前线程是否为ExecutorService线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆