【问题标题】:Multiple threads doesn't work多线程不起作用
【发布时间】: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


【解决方案1】:

基本思想确实有效,但您不能在任何线程中运行 GUI 代码;它必须在 Swing 的 UI 线程中运行。

因此,更好的解决方案是在新线程中运行“等待数据输入完成”并让主线程处理 UI。

【讨论】:

  • 哦,所以我必须检查数据是否已收集到一个新类中,并在新类中为该方法执行 .countdown?
  • 一个简单的解决方案是使用一个读取“开始”的按钮并调用一个检查和处理数据的方法。
猜你喜欢
  • 2018-09-11
  • 1970-01-01
  • 1970-01-01
  • 2021-08-07
  • 1970-01-01
  • 2014-04-30
  • 2015-07-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多