[英]Main Thread freezes all other threads inclusive java gui thread
注意:我花了很多时间研究Google和stackoverflow,但找不到答案。
我在JDialog中使用Thread.sleep(),它冻结了所有其他JDialog,JFrame和线程。
我的示例代码:
public Guitest()
{
setSize(300,300);
// create a JDialog that make guitest wait
MyDialog dlg = new MyDialog();
dlg.setSize(100,100);
dlg.setVisible(true);
while(dlg.isWait())
{
try
{
Thread.sleep(1000);
} catch (InterruptedException ex)
{
Logger.getLogger(Guitest.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("waiting mydialog");
}
}
class MyDialog extends JDialog
{
boolean wait = true;
JButton btn = new JButton("OK");
public MyDialog()
{
setSize(50,50);
btn.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
wait=false;
}
});
add(btn);
}
public boolean isWait()
{
return wait;
}
}
在这种情况下,JDialog无法正确显示:
但是必须这样:
我怎么解决这个问题。 我想让主线程等待另一个线程,有人可以在这种情况下更正我的示例代码或共享示例代码。
恕我直言,似乎您只有一个正在运行的线程。 首先,我们绘制JDialog,之后,由于等待标志,您使主线程休眠。 即。 您无法执行按钮操作侦听器,因此无法唤醒线程。
希望它能帮助理解。
Thread.Sleep()
只是休眠当前线程(即停止执行任何操作,如重绘,处理单击等),在您的情况下,该UI thread
是UI thread
。
您需要使用辅助线程。 任何需要完成的,可能花费大量时间的主要工作都需要在其自己的线程中完成,这就是您要休眠的线程。 它当前与UI组件一起运行,因此这就是为什么您看到它们冻结的原因。
一个很好的参考是swing
并发性文档http://docs.oracle.com/javase/tutorial/uiswing/concurrency/
以下内容也可能有用:
http://java.sun.com/developer/technicalArticles/Threads/swing/ http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.