Note that there are some explanatory texts on larger screens.

plurals
  1. POWait for one of several threads
    text
    copied!<p>I have a java application where the main-thread starts 2 other threads. If one of these threads terminates, the main-thread may start another thread depending on the result of the terminated thread.</p> <p>Example: The main-thread creates 2 threads: A and B. Thread A will load a picture and thread B will load another picture. If A terminates and loaded the picture successfully a new Thread C will be created which does some other stuff and so on.</p> <p>How can i do this? I do not want to use busy waiting in the main thread and check every 100ms if one of the two threads has finished. I think i cannot use a thread pool because the number of active threads (in this case A and B) will vary extremely and it's the main-threads dicision to create a new thread or not.</p> <p>This is rough sketch of the "busy waiting" solution:</p> <pre><code>public class TestThreads { private class MyThread extends Thread { volatile boolean done = false; int steps; @Override public void run() { for (int i=0; i&lt;steps; i++) { System.out.println(Thread.currentThread().getName() + ": " + i); try { Thread.sleep(1000); } catch (InterruptedException exc) { } } done = true; synchronized (this) { notify(); } } public void waitFor(long ms) { synchronized (this) { try { wait(ms); } catch (InterruptedException exc) { } } } } public void startTest() { MyThread a = new MyThread(); a.steps = 6; a.start(); MyThread b = new MyThread(); b.steps = 3; b.start(); while (true) { if (!a.done) { a.waitFor(100); if (a.done) { System.out.println("C will be started, because A is done."); } } if (!b.done) { b.waitFor(100); if (b.done) { System.out.println("C will be started, because B is done."); } } if (a.done && b.done) { break; } } } public static void main(String[] args) { TestThreads test = new TestThreads(); test.startTest(); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload