本文介绍了识别摆动EDT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何知道EDT被阻止(不是视觉上而是通过检查线程本身)?有办法吗?

How to know that EDT is blocked (not visually but by inspecting the thread itself)? is there a way?

我正要去完成我的大学最后的毕业任务,该任务有很多图表,但是对Swing EDT(通常是Java)知之甚少.

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).

看过这篇文章:

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

如果我们做一些修改块上gui组件的任务(包括调用另一个线程),那已经是正确的方法了吗?

If we do some tasks that modify gui component on the block (including calling another Thread) , is that already the correct approach?

并且由于EDT是单线程环境,所以(至少)还有一部分/示例阻止了EDT除了直接在GUI中调用Thread.start()之外.我应该调用哪种方法来识别EDT被阻止

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. 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.)

预先感谢

推荐答案

除了被Thread.sleep()阻止之外,EDT还可以例如等待异步操作时被阻止.

Apart from being blocked by Thread.sleep(), the EDT could e.g. be blocked when waiting for an asynchronous operation.

这是一个示例,在按下"Click& Wait"按钮之后,阻止EDT,直到主线程可以从控制台读取文本为止.您会注意到在输入文本之前,按钮一直处于按下状态.然后,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. You will notice that the button stays pressed until the text is entered. Then the EDT resumes and updates the label:

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);

关于何时知道EDT何时被阻止:这很棘手,但是探查器或线程转储可以帮助分析同步问题.

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 17:24