import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ThreadConditionTest {
public static void main(String[] args) {
final Print print = new Print();
// 老大
new Thread(new Runnable() {
@Override
public void run() {
while(true){
print.sub_1();
}
}
}).start();
// 老二
new Thread(new Runnable() {
@Override
public void run() {
while(true){
print.sub_2();
}
}
}).start();
// 老三
new Thread(new Runnable() {
@Override
public void run() {
while(true){
print.sub_3();
}
}
}).start();
}
}
class Print {
//控制谁该打印
int who = 1;
Lock lock = new ReentrantLock();
Condition condition1 = lock.newCondition();
Condition condition2 = lock.newCondition();
Condition condition3 = lock.newCondition();
void sub_1() {
lock.lock();
while(who != 1){
try {
condition1.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 0; i < 1; i++) {
System.out.println("sub_1" + " " + "1");
}
//改成老二该打标识
who = 2;
//叫醒老二
condition2.signal();//如果先解锁,lock.unlock();再叫醒老二,会抛出异常,因为signal()方法只能在同步代码中被调用
lock.unlock();
}
void sub_2() {
lock.lock();
while(who != 2){
try {
condition2.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 0; i < 2; i++) {
System.out.println("sub_2" + " " + "1");
}
who = 3;
condition3.signal();
lock.unlock();
}
void sub_3() {
lock.lock();
while(who != 3){
try {
condition3.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 0; i < 3; i++) {
System.out.println("sub_3" + " " + "1");
}
who =1;
condition1.signal();
lock.unlock();
}
}