简体   繁体   English

如何判断当前线程是否是事件调度thead

[英]How to judge if the current thread is the event dispatching thead

I am doing some development by Swing and I am not an expert in it.我正在通过 Swing 进行一些开发,但我不是这方面的专家。 I only know that:我只知道:

1, almost all operations on the GUI component should be done in the event dispatcher thread by run code by EventQueue.invokeLater() or EventQueue.invokeAndWait(). 1、GUI组件上的几乎所有操作都应该在事件调度线程中通过EventQueue.invokeLater()或者EventQueue.invokeAndWait()运行代码来完成。

2, if there is a time-consuming task, I should put it in another thread rather than the event dispatcher thread to avoid the GUI does not respond to the user. 2、如果有一个耗时的任务,我应该把它放在另一个线程而不是事件调度线程,以避免GUI不响应用户。

3, cannot call invokeAndWait from the event dispatcher thread. 3、不能从事件调度线程调用invokeAndWait。

So, I wish to arrange some code that may be invoked both by "another" thead or the event dispatcher thread like below:因此,我希望安排一些代码,这些代码可以由“另一个”thead 或事件调度程序线程调用,如下所示:

Runnabe rn = ...;
if (itIsTheEventDispatcherThread) {
    rn.run();
} else {
    EventQueue.invokeAndWait(rn);
}

So, how to judge if the current thread is the event dispatching thread?那么,如何判断当前线程是否为事件调度线程呢? And, is my strategy appropriate?而且,我的策略合适吗? Thanks a lot!非常感谢!

Use javax.swing.SwingUtilities.isEventDispatchThread()使用javax.swing.SwingUtilities.isEventDispatchThread()
or java awt.EventQueue.isDispatchThread() (as already using EventQueue )java awt.EventQueue.isDispatchThread() (因为已经在使用EventQueue

From documentation of SwingUtilities 1来自SwingUtilities 1文档

Returns true if the current thread is an AWT event dispatching thread.如果当前线程是 AWT 事件调度线程,则返回 true。

As of 1.3 this method is just a cover for java.awt.EventQueue.isDispatchThread().从 1.3 开始,此方法只是 java.awt.EventQueue.isDispatchThread() 的一个掩护。


1 : I prefer SwingUtilities over EventQueue even for invokeLater (at least when using Swing) 1 :我更喜欢SwingUtilities而不是EventQueue ,即使是对于invokeLater (至少在使用 Swing 时)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM