Thread-wait/notify

2465 단어 waitnotify
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);

	}
}

좋은 웹페이지 즐겨찾기