Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I would do it with semaphores. The threads are requiring their own semaphore and when finished, release the next semaphore. You can of course also do this with monitors (<code>Object#wait() and Object#notify()</code>). To ensure them running in a circular fashion, you simply let them run in endless loops and waiting for the semaphores to be filled:</p> <pre><code>import java.util.concurrent.Semaphore; public class Main { private Semaphore a = new Semaphore(1), b = new Semaphore(0), c = new Semaphore(0); public class A implements Runnable { @Override public void run() { while (true) { try { a.acquire(1); Thread.sleep((long) (Math.random() * 1000)); System.out.println("performing task A"); b.release(1); } catch (InterruptedException e) {} } } } public class B implements Runnable { @Override public void run() { while (true) { try { b.acquire(1); Thread.sleep((long) (Math.random() * 1000)); System.out.println("performing task B"); c.release(1); } catch (InterruptedException e) {} } } } public class C implements Runnable { @Override public void run() { while (true) { try { c.acquire(1); Thread.sleep((long) (Math.random() * 1000)); System.out.println("performing task C"); a.release(1); } catch (InterruptedException e) {} } } } public void startThreads() { new Thread(new A()).start(); new Thread(new B()).start(); new Thread(new C()).start(); } public static void main(String[] args) throws InterruptedException { Main ld = new Main(); ld.startThreads(); } } </code></pre> <p>The cool thing with this solution as opposed to monitors is that you can simply fill up a semaphore from the outside to start a second "thread-worm" to run in circles.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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