我想确保我的类(更新程序服务)的所有方法都在 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/