package thread;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Print implements Runnable {
private final char printChar;
private static char currentChar = 'A';
private static int count = 10;
private static Lock lock = new ReentrantLock();
private static final Condition condition_A = lock.newCondition();
private static final Condition condition_B = lock.newCondition();
private static final Condition condition_C = lock.newCondition();
Print(char printChar) {
this.printChar = printChar;
}
public void run() {
try {
lock.lock();
while (count > 0) {
if (printChar != currentChar) {
switch (printChar) {
case 'A':
try {
condition_A.await();
}
catch (InterruptedException e) {
}
break;
case 'B':
try {
condition_B.await();
}
catch (InterruptedException e) {
}
break;
case 'C':
try {
condition_C.await();
}
catch (InterruptedException e) {
}
break;
}
}
System.out.print(printChar + "(" + count + ") ~ ");
// if (count > 1) {
switch (printChar) {
case 'A':
currentChar = 'B';
condition_B.signal();
break;
case 'B':
currentChar = 'C';
condition_C.signal();
break;
case 'C':
currentChar = 'A';
condition_A.signal();
break;
// }
}
count--;
}
}
finally {
lock.unlock();
}
}
}
public class PrintThreadTest2 {
public static void main(String[] args) {
Print a = new Print('A');
Print b = new Print('B');
Print c = new Print('C');
new Thread(a).start();
new Thread(b).start();
new Thread(c).start();
}
}
输出:A(10) ~ B(9) ~ C(8) ~ A(7) ~ B(6) ~ C(5) ~ A(4) ~ B(3) ~ C(2) ~ A(1) ~ B(0) ~ C(-1) ~ 括号中为count
为什么count <= 0 的时候也能打印出来呢?
你可以在while循环的第一句添加一行:
while (count > 0) {
System.out.println(Thread.currentThread().getName()+"cout:"+count);
就能看到,每次进入循环的时候count都是>0的,最后一次进入while的时候count=1,但是由于count是全局共享变量,此时某两个个线程执行了count--操作,而当前线程再打印count的时候就成了-1了。