【发布时间】:2012-08-08 11:58:54
【问题描述】:
我正在尝试使用 GUI 界面运行代码。但是在我继续我的主要方法之前,我需要关闭所有的 GUI 窗口(我需要的一些信息是从 GUI 窗口收集的,如果没有这些信息,我将无法运行我的其余代码)。 因此,我决定使用 CountDownLatch 创建两个线程(其中一个是我的主要方法,另一个是处理我的 GUI 内容的类)。但是当我运行我的代码时,它会卡在 GUI 的末尾,并且不会继续执行我的代码。有人知道我的代码有什么问题吗?
public static void main (String[] args) throws IOException,InterruptedException{
long start = System.currentTimeMillis();
double longThreshold, shortThreshold, investment;
System.out.println("hello");
CountDownLatch startSignal = new CountDownLatch(1);
CountDownLatch stopSignal = new CountDownLatch(1);
ProgrammeSettings mySettings=new ProgrammeSettings(startSignal,stopSignal);
new Thread(mySettings).start(); // mysettings object is the GUI stuff
startSignal.countDown();
stopSignal.await();
longThreshold = mySettings.getlowerThreshold();
shortThreshold = mySettings.getupperThreshold();
investment =mySettings.getinvestment();
System.out.println("hello");
}
这也是我的 GUI 内容的 CountDownLatch 代码:
public class ProgrammeSettings implements Runnable {
private final CountDownLatch startSignal;
private final CountDownLatch stopSignal;
ProgrammeSettings(CountDownLatch startSignal, CountDownLatch doneSignal) {
this.startSignal = startSignal;
this.stopSignal = doneSignal;
}
public void graphicDesign(){
// do some GUI stuff
}
@Override
public void run() {
// TODO Auto-generated method stub
try{
startSignal.await();
graphicDesign();
stopSignal.countDown();
}
catch( InterruptedException e){
}
}
}
【问题讨论】:
-
你是说你的代码卡在
graphicDesign(),你在do some GUI stuff。您似乎没有显示与您的问题相关的代码部分。你在 EDT(事件调度线程)中运行那些 GUI 的东西吗? -
您应该只在一个 GUI 事件线程上做 GUI 工作。你想让这些线程做什么?
-
@assylias 不,它不会卡在graphicDesign() 中。它起床到 stopSignal.countDown();它退出了这个线程(这就是我在调试模式下运行代码的想法)。但是当它到达 stopSignal.await();它不再继续。当我改变 CountDownLatch stopSignal = new CountDownLatch( 2 ); to CountDownLatch stopSignal = new CountDownLatch( 1 );它完成了代码,但显然在线程完成之前它不会停止
-
@PeterLawrey 我正在尝试使用 gui 界面获取一些数字,然后使用这些数字进行一些计算。我只使用一个 GUI 事件线程,那就是 graphicsDesign()
-
您正在使用
SwingUtils.invokeLater(....)更新GUI?
标签: java multithreading user-interface countdownlatch