[英]Why should SwingUtils.invokeAndWait() method be called outside an EDT thread?
Edit : I have referred this link and I'm able to understand the codeflow of InvokeLater. 编辑 :我已经引用了这个链接 ,我能够理解InvokeLater的代码流。 My question is, why is this logic implemented this way?
我的问题是,为什么这种逻辑以这种方式实现? Are there any specific reasons?
有什么具体原因吗?
Following is my code: 以下是我的代码:
private void init()
{
JFrame jfr = new JFrame();
jfr.setSize(500, 500);
jfr.setVisible(true);
jfr.setTitle("Test");
JButton jb = new JButton("Ok");
jfr.add(jb);
jb.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
SwingUtilities.invokeAndWait(new Runnable()
{
@Override
public void run()
{
System.out.println("hello");
}
});
}
catch (Exception e1)
{
e1.printStackTrace();
}
}
});
First Question (While using InvokeAndWait
): 第一个问题 (使用
InvokeAndWait
):
Why is it implemented in such a way that it throws an InvocationTargetException
when called within EDT Thread? 为什么它以在EDT Thread中
InvocationTargetException
时抛出InvocationTargetException
的方式实现?
Second Question (while using InvokeLater
): 第二个问题 (使用
InvokeLater
):
Why InvokeLater allows this ? 为什么InvokeLater允许这个?
Well, this is my basic understanding on EDT threads: 嗯,这是我对EDT线程的基本理解:
InvokeAndWait : InvokeAndWait :
InvokeLater : InvokeLater :
EDT is the same as AWT. EDT与AWT相同。 All UI events in AWT are scheduled on a single thread called EDT.
AWT中的所有UI事件都安排在名为EDT的单个线程上。 Basically is the thread used to process UI related events in Swing.
基本上是用于在Swing中处理UI相关事件的线程。
InvokeAndWait: Basically you invoke a task on the same thread and then wait for that task to be completed. InvokeAndWait:基本上你在同一个线程上调用一个任务,然后等待该任务完成。 This would result in deadlock.
这会导致死锁。 Your method will never return cuz you are waiting for the task, the task will never run because your method will never be completed.
您的方法永远不会返回,因为您正在等待任务,任务将永远不会运行,因为您的方法永远不会完成。
InvokeLate: It works because you are not waiting for that task to be completed. InvokeLate:它的工作原理是因为您没有等待完成该任务。 You invoke it in the exact same thread, but you are not waiting for it to complete, so this won't result in deadlock.
你在完全相同的线程中调用它,但你不是在等它完成,所以这不会导致死锁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.