Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for SwingWorker to finish

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?

like image 720
user1026090 Avatar asked Nov 13 '11 13:11

user1026090


2 Answers

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

like image 63
Jan Vorcak Avatar answered Oct 01 '22 02:10

Jan Vorcak


you need to override done method from SwingWorker.

From the documentation of SwingWorker#done()

Executed on the Event Dispatch Thread after the doInBackground method is finished. The default implementation does nothing. Subclasses may override this method to perform completion actions on the Event Dispatch Thread. Note that you can query status inside the implementation of this method to determine the result of this task or whether this task has been cancelled.

public class Encrypteer3 extends SwingWorker<Void, Void>{

    @Override
    protected Void doInBackground() throws Exception {
        // background task
        return null;
    }

    @Override
    protected void done() {
        // will be executed when background execution is done
    }

}

and its the while(a.isDone()==false) { which is taking time to execute.

while(a.isDone()==false) {
    // do nothing
}
like image 45
Kowser Avatar answered Oct 01 '22 02:10

Kowser