事件调度线程究竟在何时启动?

2022-09-03 14:29:32

EDT究竟从什么时候开始?哪一行代码负责它?

我的猜测是“someSwingComponent.setVisible(true)”可以做到这一点,但我不确定。

谢谢!


答案 1

问:EDT 究竟从什么时候开始?哪一行代码负责 [f]?

Swing 的内部工作原理是特定于 JVM 的。不同的 JVM 根据不同的条件启动事件调度线程 (EDT)。但总的来说:

EDT 在收到第一个 .AWTEvent

下面的堆栈跟踪重申了这一点。以以下方法为例。main

public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setVisible(true);
}

在上面的示例中,负责启动 EDT 的代码行是frame.setVisible(true);

上述方法是在两个不同的JVM上执行的。在 处放置了一个断点。当命中断点时,将记录以下堆栈跟踪。mainEventQueue.initDispatchThread

在线程上使用 Mac 的 JDK:AWT-AppKit

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 

在线程上使用 Oracle 的 JDK for Windows:main

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 上,将呼叫 to。同样,在 Windows 上,也会调用 to。两者最终都叫.PostEventQueue.postEvent(AWTEvent)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!");
        }
    });
}

在线程上使用 Mac 的 JDK:main

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 

在线程上使用 Oracle 的 JDK for Windows:main

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

调用 to 负责启动 EDT。在这里,再次拨打了电话。SwingUtilties.invokeLaterEventQueue.postEvent(AWTEvent)


关于“我的猜测是”someSwingComponent.setVisible(true)“的想法可以解决问题,但我不确定。

不仅仅是任何调用都会启动EDT。例如,执行以下方法不会创建线程:someSwingComponent.setVisible(true)mainAWT-Event-Queue-0

public static void main(String[] args) {
    JLabel label = new JLabel();
    label.setVisible(true);
}

资源

当然,网上有很多关于EDT的资源。


答案 2
  • 您是正确的设置对于任何AWT /摇摆容器启动EDT的可见,非安全的方式

  • 初始线程是最安全的方式

  • 如果所有事件都在当前 EDT 中完成,则 isDispatchThread 返回 false

  • 在dispatchThread返回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;
    }
}

推荐