public class Key implements Runnable {
public final String s;
public volatile static String flag = "A";
public static volatile int count = 0;
public ReentrantLock lock;
public Condition condition;
public static void main(String[] args) {
final ReentrantLock lock = new ReentrantLock();
new Thread(new Key("A", lock), "Thread-A").start();
new Thread(new Key("B", lock), "Thread-B").start();
new Thread(new Key("C", lock), "Thread-C").start();
}
public Key(final String s, final ReentrantLock lock) {
this.s = s;
this.lock = lock;
this.condition = lock.newCondition();
}
@
Override public void run() {
while (true) {
lock.lock();
try {
while (!flag.equalsIgnoreCase(s)) {
try {
condition.await(10, TimeUnit.MILLISECONDS);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
if (count > 29) {
System.exit(0);
}
System.out.print(s + "-" + (count++) + "; ");
switch (flag) {
case "A":
flag = "B";
break;
case "B":
flag = "C";
break;
case "C":
flag = "A";
break;
default:
throw new RuntimeException("");
}
condition.signalAll();
}
finally {
lock.unlock();
}
}
}
}
---
这种实现可行吗?