public static Lock lock = new ReentrantLock();
public static int count = 1;
public static Condition condition1 = lock.newCondition();
public static Condition condition2 = lock.newCondition();
public static Condition condition3 = lock.newCondition();
public static Thread thread1 = new Thread(() -> {
while (count < 100) {
lock.lock();
System.out.println("A:" + count);
count ++;
condition2.signal();
try {
condition1.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.unlock();
}
});
public static Thread thread2 = new Thread(() -> {
while (count < 100) {
lock.lock();
System.out.println("B:" + count);
count ++;
condition3.signal();
try {
condition2.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.unlock();
}
});
public static Thread thread3 = new Thread(() -> {
while (count < 100) {
lock.lock();
System.out.println("C:" + count);
count ++;
condition1.signal();
try {
condition3.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.unlock();
}
});
public static void main (String[] args) {
thread1.start();
try {
Thread.sleep(1l);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread2.start();
try {
Thread.sleep(1l);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread3.start();
}