Mehdi
Mehdi

Reputation: 21

Multiple threads doesn't work

I am trying to run a code with a GUI interface. But I need the GUI windows all to be closed before I proceed with my main method, (some of the information that I need is collected from the GUI windows and I cant run the rest of my code without that information). So, I decided to use CountDownLatch to create two threads (one of them being my main method and the other one the class with handles my GUI stuff). But when I run my code it gets stuck at the end of the GUI and it doesn't proceed with my code. does anyone know what is wrong with my code?

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");
}

also here is my code for CountDownLatch of the GUI stuff:

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){

    }

}

}

Upvotes: 1

Views: 186

Answers (1)

Aaron Digulla
Aaron Digulla

Reputation: 328614

The basic idea does work but you can't run the GUI code in any thread; it must run in Swing's UI thread.

So a better solution is to run your "wait for completion of the data entry" in a new thread and let the main thread handle the UI.

Upvotes: 2

Related Questions