EDT何时开始?什么代码行负责呢?
我的猜测是“someSwingComponent.setVisible(true)”可以解决问题,但我不确定。
谢谢!
答案 0 :(得分:14)
Swing的内部工作原理是特定于JVM的。不同的JVM根据不同的标准启动事件调度线程(EDT)。一般来说:
EDT在收到第一个
AWTEvent
时开始。
下面的堆栈跟踪重申了这一点。例如,使用以下main
方法。
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setVisible(true);
}
在上面的示例中,负责启动EDT的代码行是frame.setVisible(true);
上面的main
方法在两个不同的JVM上执行。断点位于EventQueue.initDispatchThread
。当断点被击中时,注意到以下堆栈跟踪。
在AWT-AppKit
主题上使用Mac的JDK:
EventQueue.initDispatchThread() line: 906
EventQueue.wakeup(boolean) line: 1109
NativeMethodAccessorImpl.invoke0(Method, Object, Object[]) line: not available [native method]
NativeMethodAccessorImpl.invoke(Object, Object[]) line: 39
DelegatingMethodAccessorImpl.invoke(Object, Object[]) line: 25
Method.invoke(Object, Object...) line: 597
SunToolkit.wakeupEventQueue(EventQueue, boolean) line: 348
PostEventQueue.postEvent(AWTEvent) line: 2137
SunToolkit.postEvent(AppContext, AWTEvent) line: 583
SunToolkit.executeOnEventHandlerThread(PeerEvent) line: 654
SunToolkit.executeOnEventHandlerThread(Object, Runnable) line: 631
EventFactoryProxy.windowMoved(CWindow) line: 89
在main
主题上使用Oracle的JDK for Windows:
java.awt.EventQueue.initDispatchThread() line: 861
java.awt.EventQueue.postEventPrivate(java.awt.AWTEvent) line: 199
java.awt.EventQueue.postEvent(java.awt.AWTEvent) line: 180
javax.swing.RepaintManager.scheduleProcessingRunnable(sun.awt.AppContext) line: 1369
javax.swing.RepaintManager.nativeAddDirtyRegion(sun.awt.AppContext, java.awt.Container, int, int, int, int) line: 548
javax.swing.SwingPaintEventDispatcher.createPaintEvent(java.awt.Component, int, int, int, int) line: 45
sun.awt.windows.WFramePeer(sun.awt.windows.WComponentPeer).postPaintIfNecessary(int, int, int, int) line: 741
sun.awt.windows.WFramePeer(sun.awt.windows.WComponentPeer).handlePaint(int, int, int, int) line: 736
sun.java2d.d3d.D3DScreenUpdateManager.repaintPeerTarget(sun.awt.windows.WComponentPeer) line: 274
sun.java2d.d3d.D3DScreenUpdateManager.createScreenSurface(sun.awt.Win32GraphicsConfig, sun.awt.windows.WComponentPeer, int, boolean) line: 175
...
sun.awt.windows.WToolkit.createFrame(java.awt.Frame) line: 383
javax.swing.JFrame(java.awt.Frame).addNotify() line: 460
javax.swing.JFrame(java.awt.Window).show() line: 859
javax.swing.JFrame(java.awt.Component).show(boolean) line: 1584
javax.swing.JFrame(java.awt.Component).setVisible(boolean) line: 1536
javax.swing.JFrame(java.awt.Window).setVisible(boolean) line: 842
Example.main(java.lang.String[]) line: 113
在Mac上,拨打PostEventQueue.postEvent(AWTEvent)
。同样在Windows上,会调用java.awt.EventQueue.postEvent(java.awt.AWTEvent)
。两人最终都会打电话给EventQueue.initDispatchThread
。
作为另一个示例,请考虑以下main
方法:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
System.out.println("Start!");
}
});
}
在main
主题上使用Mac的JDK:
EventQueue.initDispatchThread() line: 906 [local variables unavailable]
EventQueue.postEventPrivate(AWTEvent) line: 227
EventQueue.postEvent(AWTEvent) line: 208
EventQueue.invokeLater(Runnable) line: 1048
SwingUtilities.invokeLater(Runnable) line: 1267
Example.main(String[]) line: 31
在main
主题上使用Oracle的JDK for Windows:
java.awt.EventQueue.initDispatchThread() line: 861
java.awt.EventQueue.postEventPrivate(java.awt.AWTEvent) line: 199
java.awt.EventQueue.postEvent(java.awt.AWTEvent) line: 180
java.awt.EventQueue.invokeLater(java.lang.Runnable) line: 999
javax.swing.SwingUtilities.invokeLater(java.lang.Runnable) line: 1267
致SwingUtilties.invokeLater
的电话负责启动EDT。这里再次呼叫EventQueue.postEvent(AWTEvent)
。
不只是对someSwingComponent.setVisible(true)
的任何调用都会启动EDT。例如,执行以下main
方法不会创建AWT-Event-Queue-0
线程:
public static void main(String[] args) {
JLabel label = new JLabel();
label.setVisible(true);
}
当然,网上有很多关于EDT的资源。
答案 1 :(得分:1)
只要组件通过调用Toolkit.getEventQueue()请求访问事件队列,就会启动Event Dispatch Thread。这可以在调用Component.show()时完成(与Component.setVisible()相同),但也有其他调用可以触发此初始化,如Component.repaint()。获得对事件队列的引用后,可以使用EventQueue.postEvent()将作业添加到其中。此方法检查EDT是否存在,如果不存在,则使用initDispatchThread()创建它。
阻止它启动的唯一方法是使用“-Djava.awt.headless = true”标志以无头模式(一起禁用AWT)启动JVM。但这基本上是你可以与它进行的唯一低级互动。
应始终在EDT上调用Component的setVisible方法(就像您对Swing / AWT组件所做的任何其他修改一样)。您可以通过告诉Java在EDT上执行代码来使用EDT。最简单的方法是使用SwingUtilities.invokeLater()。这将调度您的Thread(您的Runnable实现)从EDT执行。这是开发人员应该与EDT进行的唯一交互。您不应该与EDT进行任何低级别的交互,例如暂停或中止线程。
答案 2 :(得分:1)
对于任何启动EDT的AWT / Swing容器,你都是正确的setVisible,非安全的方式
Initial Thread 是最安全的方式
如果所有事件都在当前的EDT中完成,则isDispatchThread返回false
在isDispatchThread返回false的情况下,任何Swing线程安全方法都可以使EDT存活,最安全的方法是从invokeLater()
测试代码
import java.awt.Color;
import java.awt.EventQueue;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
public class IsThereEDT {
private ScheduledExecutorService scheduler;
private AccurateScheduledRunnable periodic;
private ScheduledFuture<?> periodicMonitor;
private int taskPeriod = 30;
private SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
private Date dateRun;
private JFrame frame1 = new JFrame("Frame 1");
public IsThereEDT() {
scheduler = Executors.newSingleThreadScheduledExecutor();
periodic = new AccurateScheduledRunnable() {
private final int ALLOWED_TARDINESS = 200;
private int countRun = 0;
private int countCalled = 0;
private int maxCalled = 10;
@Override
public void run() {
countCalled++;
if (countCalled < maxCalled) {
if (countCalled % 3 == 0) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
System.out.println("Push a new event to EDT");
frame1.getContentPane().setBackground(Color.red);
isThereReallyEDT();
}
});
} else {
if (this.getExecutionTime() < ALLOWED_TARDINESS) {
countRun++;
isThereReallyEDT(); // non on EDT
}
}
} else {
System.out.println("Terminating this madness");
System.exit(0);
}
}
};
periodicMonitor = scheduler.scheduleAtFixedRate(periodic, 0, taskPeriod, TimeUnit.SECONDS);
periodic.setThreadMonitor(periodicMonitor);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
isThereReallyEDT();
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.getContentPane().add(new JLabel("Hello in frame 1"));
frame1.pack();
frame1.setLocation(100, 100);
frame1.setVisible(true);
}
});
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
Logger.getLogger(IsThereEDT.class.getName()).log(Level.SEVERE, null, ex);
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame2 = new JFrame("Frame 2");
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame2.getContentPane().add(new JLabel("Hello in frame 2"));
frame2.pack();
frame2.setLocation(200, 200);
frame2.setVisible(true);
isThereReallyEDT();
}
});
}
private void isThereReallyEDT() {
dateRun = new java.util.Date();
System.out.println(" Time at : " + sdf.format(dateRun));
if (EventQueue.isDispatchThread()) {
System.out.println("EventQueue.isDispatchThread");
} else {
System.out.println("There isn't Live EventQueue.isDispatchThread, why any reason for that ");
}
if (SwingUtilities.isEventDispatchThread()) {
System.out.println("SwingUtilities.isEventDispatchThread");
} else {
System.out.println("There isn't Live SwingUtilities.isEventDispatchThread, why any reason for that ");
}
System.out.println();
}
public static void main(String[] args) {
IsThereEDT isdt = new IsThereEDT();
}
}
abstract class AccurateScheduledRunnable implements Runnable {
private ScheduledFuture<?> thisThreadsMonitor;
public void setThreadMonitor(ScheduledFuture<?> monitor) {
this.thisThreadsMonitor = monitor;
}
protected long getExecutionTime() {
long delay = -1 * thisThreadsMonitor.getDelay(TimeUnit.MILLISECONDS);
return delay;
}
}