user1026090
user1026090

Reputation: 458

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?

Upvotes: 7

Views: 11931

Answers (3)

mKorbel
mKorbel

Reputation: 109815

I want to wait for my SwingWorker to finish working, and then I want 
to execute another SwingWorker.

better than checking if(isDone) would be implements Executor, but in all cases (meaning SwingWorker) you have to check this thread, how to get exception(s) from nested method(s)

Upvotes: 0

Kowser
Kowser

Reputation: 8261

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
}

Upvotes: 3

Jan Vorcak
Jan Vorcak

Reputation: 19989

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

Upvotes: 3

Related Questions