当前位置: 代码迷 >> 综合 >> 多线程——waiting-notify机制实例(三个人打水)
  详细解决方案

多线程——waiting-notify机制实例(三个人打水)

热度:44   发布时间:2024-01-10 07:27:48.0

//三个学生到一个水龙头下排队取水,三人都取完水后一起离开。//这里涉及到如何判断三个人都取完水。如果用普通的静态成员,势必会要用无限循环来等待。更好的办法是用 wait-notify 机制。
//前两个学生取完水后都 wait,最后一个学生取完水后 notify,这样就能一起离开了。下面是代码示例:package com.cs;/*** * @author Administrator 三个学生排队取水,取完后一起离开*/
public class Test {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;}@Overridepublic 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;}
}
 
  相关解决方案