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

Java之wait()和notify() 博客分类: Java  

程序员文章站 2024-02-25 21:35:45
...

概述:

Java多线程并发模型中的实现可以基于wait()和notify()

生产者消费者代码:

消费者:

class Customer implements Runnable {
	public void run() {
		while (true) {
			synchronized (TestConcurrentThread.lock) {

				if (TestConcurrentThread.list.size() > 0) {
					TestConcurrentThread.list.remove(TestConcurrentThread.list
							.size() - 1);
					System.out.println("***Customer item items size is :"
							+ TestConcurrentThread.list.size());
				} else {
					try {
						TestConcurrentThread.lock.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}

			}

		}

	}

}

生产者:

class Producer implements Runnable {
	public void run() {
		while (true) {
			synchronized (TestConcurrentThread.lock) {
				if (TestConcurrentThread.list.size() > 1000) {
					TestConcurrentThread.lock.notify();
					continue;
				}
				TestConcurrentThread.list.add("abc");
				System.out.println("***Producer item items size is :"
						+ TestConcurrentThread.list.size());
				TestConcurrentThread.lock.notify();
			}
		}
	}
}

调用:

public class TestConcurrentThread {
	public static final Object lock = new Object();
	public static List<String> list = new ArrayList<String>();
	public static void main(String[] args) {
		Thread customerThread = new Thread(new Customer());
		customerThread.start();
		Thread producerThread = new Thread(new Producer());
		producerThread.start();
	}

}

结论:

1.有wait(),notify()的地方必须有synchronized

2.wait()之后必须通过notify()系唤醒

3.notify()系的时候需要在synchronized代码块执行完成之后才能释放锁