java:简单使用wait,notify

简单使用wait,notify的小例子

import java.util.Random;

public class TestWait {

	/**
	 * 同步锁
	 */
	private static Object lock = new Object();

	/**
	 * 计算结果
	 */
	private static String result = null;

	/**
	 * 获取计算结果
	 */
	public static synchronized String getResult() {
		return result;
	}

	/**
	 * 设置计算结果
	 */
	public static synchronized void setResult(String result) {
		TestWait.result = result;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// 初始化
		Random random = new Random();
		setResult(random.nextBoolean() ? "init" : null);
		// 起线程,计算
		new WaitThread().start();
		new NotifyThread().start();
	}

	/**
	 * 等待线程
	 * 
	 */
	static class WaitThread extends Thread {
		@Override
		public void run() {
			if (getResult() == null) {
				// 无缓存结果
				synchronized (lock) {
					try {
						// 等待 最大等待时间
						System.out.println("wait begin");
						lock.wait(10000);
						System.out.println("wait end");
					} catch (InterruptedException e) {
						e.printStackTrace();
					} catch (IllegalArgumentException e) {
						e.printStackTrace();
					} catch (IllegalMonitorStateException e) {
						e.printStackTrace();
					}
				}
			}
			
			// 打印缓存结果
			System.out.println("result: " + getResult());
		}
	}

	/**
	 * 通知线程
	 * 
	 */
	static class NotifyThread extends Thread {
		@Override
		public void run() {
			// 1、后台计算
			backgroundStatistics();
			// 2、发送通知
			synchronized (lock) {
				try {
					System.out.println("notify begin");
					lock.notifyAll();
					System.out.println("notify end");
				} catch (IllegalMonitorStateException e) {
					e.printStackTrace();
				}
			}
		}

		private void backgroundStatistics() {
			// 计算...
			Random random = new Random();
			int sleepTime = random.nextInt(15) * 1000;
			try {
				System.out.println("backgroundStatistics begin: " + sleepTime);
				// 休眠
				Thread.sleep(sleepTime);
				System.out.println("backgroundStatistics end");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			setResult("backgroundStatistics result!");
		}
	}
}


你可能感兴趣的:(java:简单使用wait,notify)