Wait for SwingWorker to finish

I want to wait until my SwingWorker completes, and then I want to run another SwingWorker. In this case, Encrypteer3 is the class that extends SwingWorker.

My code is:

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 the processor when doing this). I think the problem is that it constantly checks to see if the thread is running and what makes it so intense with the CPU.

There is no join () method in the SwingWorker class. How can I make this less intense?

+6
source share
3 answers

I think using an empty loop is a bad idea, SwingWorker has

 protected void done() 

where you can define the code to be executed upon completion, then you can use listerners and firing for this if you want to execute outside of SW

+3
source

you need to override the done method from SwingWorker .

From the SwingWorker # done () documentation

Runs in the event dispatch stream after the doInBackground method completes. The default implementation does nothing. Subclasses can override this method to perform completion actions in Thread Dispatch Thread. Please note that you can request a status within the implementation of this method to determine the result of this task or cancel this task.

 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 while(a.isDone()==false) { , which takes time to execute.

 while(a.isDone()==false) { // do nothing } 
+3
source
 I want to wait for my SwingWorker to finish working, and then I want to execute another SwingWorker. 

better than checking if(isDone) will execute Executor , but in all cases (which means SwingWorker) you should check this thread , how to get an exception from the nested method (s)

0
source

Source: https://habr.com/ru/post/901378/


All Articles