/**
* 三个学生排队取水,取完后一起离开
*
* @author yiding.he
*/
public class SyncDemo_FetchingWater {
private static final ValueLock water = new ValueLock();
public static void main(String[] args) {
String[] student_names = {"甲", "乙", "丙"};
for (String student_name : student_names) {
new Student(student_name).start();
}
}
// 学生
private static class Student extends Thread {
private String name;
private Student(String name) {
this.name = name;
}
@Override
public void run() {
try {
synchronized (water) {
Thread.sleep(1000);
System.out.println("学生" + name + "取完了水。");
water.value++;
if (water.value == 3) {
System.out.println("三个人都取完了水。");
water.notifyAll(); // 只要执行了这个,学生们都会离开。
} else {
water.wait(); // 同时释放了锁,下一个线程进入
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("学生" + name + "离开了。");
}
}
// 带值的锁
private static class ValueLock {
public int value;
}
}