简体   繁体   English

识别摆动EDT

[英]Recognizing Blocked Swing EDT

How to know that EDT is blocked (not visually but by inspecting the thread itself)? 如何知道EDT是否被阻止(不是在视觉上而是通过检查线程本身)? is there a way? 有办法吗?

I'm on the way to my final university task for graduation that have bunch of charts , but have little knowledge of Swing EDT (Java generally). 我正要去完成大学的最后一项毕业任务,该任务有很多图表,但是对Swing EDT(一般来说是Java)了解很少。

have look at this piece: 看一下这块:

 SwingUtilities.invokeLater(new Runnable() {
         public void run() {
             //  task here
         }
    });

If we do some tasks that modify gui component on the block (including calling another Thread) , is that already the correct approach? 如果我们做一些修改块上gui组件的任务(包括调用另一个Thread),那已经是正确的方法了吗?

And since EDT is single threaded environment, what else (at least) one part/example that blocking EDT other than calling Thread.start() directly inside the GUI. 而且由于EDT是单线程环境,除了直接在GUI内部调用Thread.start()之外,还有其他(至少)一个阻止EDT的部分/示例。 What method I should call to recognize that the EDT is blocked 我应该调用哪种方法来识别EDT被阻止

Before I asked this, I've read some documentation (but it fails explains to me how to prevent blocking EDT in simple explanation.) 在我问这个问题之前,我已经阅读了一些文档(但是在简单的解释中,它无法为我解释如何防止阻塞EDT。)

Thanks in advance 提前致谢

Apart from being blocked by Thread.sleep() , the EDT could eg be blocked when waiting for an asynchronous operation. 除了被Thread.sleep()阻止之外,EDT还可以例如在等待异步操作时被阻止。

Here's an example that -- after the "Click & Wait" button is pressed -- blocks the EDT until the main thread can read text from the console. 这是一个示例,在按下“ Click&Wait”按钮之后,阻止EDT,直到主线程可以从控制台读取文本为止。 You will notice that the button stays pressed until the text is entered. 您会注意到在输入文本之前,按钮一直处于按下状态。 Then the EDT resumes and updates the label: 然后,EDT恢复并更新标签:

CompletableFuture<String> future = new CompletableFuture<>();

SwingUtilities.invokeLater(() -> {
    JFrame f = new JFrame("EDT Blocking Example");
    f.setSize(200, 200);
    JLabel label = new JLabel();
    JButton button = new JButton("Click & Wait");
    button.addActionListener(l -> {
        try {
            // calling get() will block the EDT here...
            String text = future.get();
            label.setText(text);
        } catch (Exception e) {
            e.printStackTrace();
        }
    });
    JPanel content = new JPanel();
    content.add(button);
    content.add(label);
    f.setContentPane(content);
    f.setVisible(true);
});
System.out.print("Enter some text: ");
String input = new Scanner(System.in).nextLine();

future.complete(input);

As for knowing when the EDT is blocked: This is tricky, but a profiler or a thread dump can help in analyzing synchronization issues. 至于知道何时阻止EDT:这很棘手,但是探查器或线程转储可以帮助分析同步问题。

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

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