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 38 39 40
| public class ABCPrinter { private static final Object lock = new Object(); private volatile static int state = 0;
public static void main(String[] args) { new Thread(new PrintTask('A', 0), "Thread-A").start(); new Thread(new PrintTask('B', 1), "Thread-B").start(); new Thread(new PrintTask('C', 2), "Thread-C").start(); }
static class PrintTask implements Runnable { private final char targetChar; private final int targetState;
public PrintTask(char targetChar, int targetState) { this.targetChar = targetChar; this.targetState = targetState; }
@Override public void run() { synchronized (lock) { try { while (state < 100) { while ((state % 3) != targetState && state < 100) { lock.wait(); } if(state < 100){ System.out.println(Thread.currentThread().getName() + " - " + state + " : " + targetChar); state++; lock.notifyAll(); } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } } }
|