Wait for SwingWorker to finish

user1026090 picture user1026090 · Nov 13, 2011 · Viewed 10.2k times · Source

I want to wait for my SwingWorker to finish working, and then I want to execute another SwingWorker. In this case Encrypteer3 is a class that extends the SwingWorker.

My code:

    input = txtTekst.getText();
    key = txtKey.getText();
    System.out.println("thread1 start");
    Encrypteer3 a = new Encrypteer3();
    a.execute();
    while(a.isDone()==false){
        // do nothing
    }
    input = output;
    key = txtKey1.getText();
    System.out.println("thread2 start");
    Encrypteer3 b = new Encrypteer3();
    b.execute();
    while(b.isDone()==false){
        // do nothing
    }

This makes my GUI freeze and uses a lot of CPU (java uses about 95% of CPU when executing this). I think the problem is that it's constantly checking if the thread is done and that's what makes it so CPU intensive.

There is no join() method on a SwingWorker class. How can I make this less CPU intensive?

Answer

Jan Vorcak picture Jan Vorcak · Nov 13, 2011

I think using empty loop is bad idea, SwingWorker has

protected  void done()

where you can define code executed when it's finished, then you can use listerners and firing actions for that if you want to execute outside of SW