1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| public class multiThreadedPrinting3 { private static final int count = 3; private static final Semaphore semA = new Semaphore(1); private static final Semaphore semB = new Semaphore(0); private static final Semaphore semC = new Semaphore(0);
public static void main(String[] args) { new Thread(new Task("A", semA, semB)).start(); new Thread(new Task("B", semB, semC)).start(); new Thread(new Task("C", semC, semA)).start(); }
private static class Task implements Runnable { private final String value; private final Semaphore current; private final Semaphore next;
public Task(String value, Semaphore current, Semaphore next) { this.value = value; this.current = current; this.next = next; }
@Override public void run() { for(int i = 0; i < count; i ++) { try { current.acquire(); System.out.println(value); next.release(); } catch (Exception e) { e.printStackTrace(); } } } } }
|