Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Nice question, I have written a small class that will demonstrate how Semaphores can be used to run threads in a sequence. Hope this helps:</p> <pre><code>public class LockingDemo{ private Semaphore a = new Semaphore(0); private Semaphore b = new Semaphore(0); private Semaphore c = new Semaphore(1); class A implements Runnable{ @Override public void run() { try { c.acquire(1); System.out.println("Doing A"); a.release(1); } catch (InterruptedException e) { e.printStackTrace(); } } } class B implements Runnable{ @Override public void run() { try{ a.acquire(1); System.out.println("Doing B"); b.release(1); } catch (InterruptedException e) { e.printStackTrace(); } } } class C implements Runnable{ @Override public void run() { try{ b.acquire(1); System.out.println("Doing C"); c.release(1); } catch (InterruptedException e) { e.printStackTrace(); } } } public void a() throws InterruptedException{ new Thread(new A()).start(); } public void b() throws InterruptedException{ new Thread(new B()).start(); } public void c() throws InterruptedException{ new Thread(new C()).start(); } public static void main(String[] args) throws InterruptedException { LockingDemo ld = new LockingDemo(); System.out.println("FIRST RUN CALLING B -&gt; A -&gt; C"); ld.b(); ld.a(); ld.c(); Thread.currentThread().sleep(2000); System.out.println("SECOND RUN CALLING C -&gt; B -&gt; A"); ld.c(); ld.b(); ld.a(); } } </code></pre> <p>Here is the OUTPUT</p> <pre><code>FIRST RUN CALLING B -&gt; A -&gt; C Doing A Doing B Doing C SECOND RUN CALLING C -&gt; B -&gt; A Doing A Doing B Doing C </code></pre>
    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