并发编程基础之wait以及notify的用法

一:概念java

线程通讯中常常用到wait和notify,顾名思义,wait即让当前线程处于等待状态,notify通知锁对象线程

上的另外一个线程被唤醒,这里的唤醒是指能够去争夺锁资源,nofityAll是唤醒该对象上面全部处于对象

wait状态的线程blog

 

二:示例资源

线程t2一运行就处于wait等待状态,而后线程t1运行notify,唤醒线程t2get

/**
 * 
 */
package com.day2;

/**
 * @author Administrator
 *
 */
public class NotifyWaitThreadDemo {

	private int count;

	public static void main(String[] args) {

		NotifyWaitThreadDemo demo = new NotifyWaitThreadDemo();

		Thread t1 = new Thread("t1") {
			public void run() {
				synchronized (demo) {
					for (int i = 0; i < 100; i++) {
						demo.count = i;
						if (demo.count == 50) {
							System.out.println(Thread.currentThread().getName()+"发出通知");
							demo.notify();
						}
					}
				}

			}
		};

		Thread t2 = new Thread("t2") {
			public void run() {
				while (true) {
					synchronized (demo) {
						System.out.println(Thread.currentThread().getName() + "开始等待");
						try {
							demo.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					System.out.println(Thread.currentThread().getName() + "跳出等待");
					System.out.println("demo.count" + demo.count);
					break;
				}

			}
		};
		
		t2.start();
		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		t1.start();
		
	}
}

  

若是还有一个线程t3也处于wait状态,那么t1线程若是想唤醒t1和t3,就须要使用notifyAllit

/**
 * 
 */
package com.day2;

/**
 * @author Administrator
 *
 */
public class NotifyWaitThreadDemo {

	private int count;

	public static void main(String[] args) {

		NotifyWaitThreadDemo demo = new NotifyWaitThreadDemo();

		Thread t1 = new Thread("t1") {
			public void run() {
				synchronized (demo) {
					for (int i = 0; i < 100; i++) {
						demo.count = i;
						if (demo.count == 50) {
							System.out.println(Thread.currentThread().getName()+"发出通知");
							//demo.notify();
							demo.notifyAll();
						}
					}
				}

			}
		};

		Thread t2 = new Thread("t2") {
			public void run() {
				while (true) {
					synchronized (demo) {
						System.out.println(Thread.currentThread().getName() + "开始等待");
						try {
							demo.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					System.out.println(Thread.currentThread().getName() + "跳出等待");
					System.out.println("demo.count" + demo.count);
					break;
				}

			}
		};
		
		Thread t3 = new Thread("t3") {
			public void run() {
				while (true) {
					synchronized (demo) {
						System.out.println(Thread.currentThread().getName() + "开始等待");
						try {
							demo.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					System.out.println(Thread.currentThread().getName() + "跳出等待");
					break;
				}

			}
		};
		t2.start();
		t3.start();
		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		t1.start();
		
	}
}

  

运行结果:io

t2开始等待
t3开始等待
t1发出通知
t3跳出等待
t2跳出等待
demo.count99
相关文章
相关标签/搜索