WaitNotifyDemo

原创
2017/07/28 08:51
阅读数 52
package com.my.demo;
import java.io.IOException;

public class WaitNotifyDemo {
	public static void main(String[] args) throws InterruptedException, IOException {
		Object lock = new Object();
		//They share the same lock.
		new NotifyThread("notify01", lock).start();
		new WaitThread("waiter01", lock).start();
		new WaitThread("waiter02", lock).start();
	}
}

class WaitThread extends Thread {
	private Object lock;
	public WaitThread(String name, Object lock) {
		super(name);
		this.lock = lock;
	}

	public void run() {
		synchronized (lock) {
			System.out.println(getName() + " waiting!");
			long waitTime = System.currentTimeMillis();
			try {
				lock.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			waitTime = System.currentTimeMillis() - waitTime;
			System.out.println(getName() + " wait time: " + waitTime);
		}
	}
}

class NotifyThread extends Thread {
	private Object lock;
	public NotifyThread(String name, Object lock) {
		super(name);
		this.lock = lock;
	}

	public void run() {
		try {
			System.in.read();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		synchronized (lock) {
			lock.notifyAll();
		}
	}
};

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部