JAVA ----- wait and notifyAll usage

Only learning, infringement will be deleted , if wrong, please inform

A, wait and notifyAll

package Suo8;

public class Huanxing {
	private static final String XIAOMING_STRING = "小明";
	private static volatile boolean zhuangtai = false;
	public static void xiaoming() {
		synchronized (XIAOMING_STRING) {
			System.out.println("小明在睡觉,三秒等待小李唤醒!");
			try {
				XIAOMING_STRING.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("小明起床,动作结束");
		}
	}
	public static void xiaoli() {
		System.out.println("三秒钟时间到,小李准备唤醒小明");
		synchronized (XIAOMING_STRING) {
			XIAOMING_STRING.notifyAll();
		}
	}
	public static void main(String[] args) throws InterruptedException {
		Thread thread = new Thread() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				xiaoming();
			}
		};
		thread.start();
		while (!zhuangtai) {
			for (int i = 1; i <= 3; i++) {
				Thread.sleep(1000);
				System.out.println("已过去"+i+"秒");
			}
			zhuangtai = true;
		}
		Thread thread1 = new Thread() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				xiaoli();
			}
		};
		thread1.start();
	}
}

Released eight original articles · won praise 2 · Views 100

Guess you like

Origin blog.csdn.net/fenghuaqingjun/article/details/104465038