欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Thread-wait/notify

程序员文章站 2022-07-06 12:31:50
...

java 线程通过对象的Wait和Notify进行同步,但是存在一定的危险性

其重点是:wait 和 notify 的 时间点

举例:

package com.horizon.thread.aqs;

public class NotSafeWaitNotify {

	private static StringBuffer lock = new StringBuffer();

	public static void main(String[] args) throws Exception {
		// testWaitAfterNotify();
		//testWaitBeforeNotify();
		testWaitAfterNotifyV2();
	}

	/**
	 * 先notify 后wait,不能正常工作
	 */
	private static void testWaitAfterNotify() throws Exception {
		Thread modifyThread = new Thread() {
			@Override
			public void run() {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

				synchronized (lock) {
					lock.append("1000");
					lock.notify();
				}
			}
		};

		modifyThread.start();

		Thread.sleep(2000);
		synchronized (lock) {
			lock.wait();
		}

		System.out.println(lock);

	}

	/**
	 * 先notify 后wait,不能正常工作 
	 * 改进思路:先判断是否已经有结果
	 */
	private static void testWaitAfterNotifyV2() throws Exception {
		Thread modifyThread = new Thread() {
			@Override
			public void run() {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

				synchronized (lock) {
					lock.append("1000");
					lock.notify();
				}
			}
		};

		modifyThread.start();

		Thread.sleep(2000);
		synchronized (lock) {
			//先判断是否已经有结果
			if (lock.length() < 0) {
				lock.wait();
			}
		}

		System.out.println(lock);

	}

	/**
	 * 先wait 后notify,正常工作
	 */
	private static void testWaitBeforeNotify() throws Exception {
		Thread modifyThread = new Thread() {
			@Override
			public void run() {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

				synchronized (lock) {
					lock.append("1000");
					lock.notify();
				}
			}
		};

		modifyThread.start();

		synchronized (lock) {
			lock.wait();
		}

		System.out.println(lock);

	}
}

 

相关标签: wait notify