`
小网客
  • 浏览: 1216487 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Java之wait()和notify()

    博客分类:
  • Java
 
阅读更多

概述:

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代码块执行完成之后才能释放锁

0
2
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics