java Object类wait和notify Demo

import java.util.logging.Level;
import java.util.logging.Logger;

class Task extends Thread {

	@Override
	public void run() {
		try {
			synchronized (this) {
				Thread t = Thread.currentThread();
				System.out.println(t.getId() + t.getName() + ":task start, wait for notify...");
				this.wait();
				System.out.println(t.getId() + t.getName() + ":task continue...");
			}
		} catch (InterruptedException ex) {
			Logger.getLogger(Task.class.getName()).log(Level.SEVERE, null, ex);
		}
	}
}

public class WaitDemo {

	public static void main(String[] args) throws InterruptedException {
		Task task = new Task();
		Thread t = Thread.currentThread();
		System.out.println(t.getId() + t.getName() + ":task start...");
		task.start();
		Thread.sleep(2000);
		synchronized (task) {
			task.notify();
		}
	}
}

  

posted @ 2012-11-20 20:12  Leo Forest  阅读(466)  评论(0编辑  收藏  举报