除了被阻止外
Thread.sleep(),EDT还可以例如在等待异步操作时被阻止。
这是一个示例,在按下“
Click&Wait”按钮之后,将阻止EDT,直到主线程可以从控制台读取文本为止。您会注意到在输入文本之前,按钮一直处于按下状态。然后,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);至于知道何时阻止EDT:这很棘手,但是探查器或线程转储可以帮助分析同步问题。



