简体   繁体   中英

Recognizing Blocked Swing EDT

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

Apart from being blocked by Thread.sleep() , the EDT could eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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