Recognizing Blocked Swing EDT

安稳与你 提交于 2020-03-27 06:54:47

问题


How to know that EDT is blocked (not visually but by inspecting the thread itself)? 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).

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?

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

Before I asked this, I've read some documentation (but it fails explains to me how to prevent blocking EDT in simple explanation.)

Thanks in advance


回答1:


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

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

As for knowing when the EDT is blocked: This is tricky, but a profiler or a thread dump can help in analyzing synchronization issues.



来源:https://stackoverflow.com/questions/30881263/recognizing-blocked-swing-edt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!