Java 检测当前线程是否为服务线程
我想确保类(更新程序服务)的所有方法都在Java 检测当前线程是否为服务线程,java,multithreading,executorservice,Java,Multithreading,Executorservice,我想确保类(更新程序服务)的所有方法都在ExecutorService的线程中调用(只要有一个线程)。没有给出方法的顺序,因此那些公共的方法可能会从执行器的线程和一些其他线程(主要是GUI线程)调用 我的代码: // Instantiated lazy using synchronized getter - I decided not to bother with shared locks private ExecutorService executor; /** * Prov
ExecutorService
的线程中调用(只要有一个线程)。没有给出方法的顺序,因此那些公共的方法可能会从执行器的线程和一些其他线程(主要是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的线程中运行?如果您为Executor服务的实现(例如a)提供了a的实现,则可以记录工厂创建的线程(通过引用或id)稍后对该线程工厂执行查找,以确定它们是否是由工厂创建的,从而确定执行器线程哦,我有点困惑。executor服务不使用事件循环逐个执行事件/操作?可能只是我甚至不是我想要使用的线程执行器服务。当然这不是你的错,我想我会调查一下并接受你的答案。@TomášZato执行者使用事件循环,运行ThreadFactory创建的线程。您可以创建一个子类Thread,只需检查MyThread的Thread.currentThread()instanceof
,我还没有对它进行测试,但我实现了ThreadFactory,以便它生成一个线程,然后通过getter公开。我用它来做检查。不幸的是,它向updater类添加了另一个私有属性(工厂实例)。