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代码块执行完成之后才能释放锁
推荐阅读
-
Gson之map解析 博客分类: Java
-
Java之wait()和notify() 博客分类: Java
-
一位10年Java工作经验的架构师聊Java和工作经验 博客分类: javaweb javaweb工作经验
-
Java获取jsp中的值和jsp中获取Java中的值 博客分类: jsp jspjava值
-
java编程思想笔记(六)接口和抽象类 博客分类: java编程思想笔记 javajavawebjava编程思想
-
Java I/O 深入学习( 二)之数组类输入输出流 博客分类: J2EE ByteArrayInputStreamByteArrayOutputStream
-
Java IO 之ByteArrayInputStream & ByteArrayOutputStream 博客分类: 再学JavaSE javaioByteArrayInputStreamByteArrayOutputStream
-
swing 文本域的undo和右键开始菜单 博客分类: java swingJava undo文本域右键菜单JPopupMenuUndoManager
-
json-lib 之jsonConfig详细使用 博客分类: Java JSON JSONjson-libjsonConfig
-
json-lib 序列化和反序列化 博客分类: Java json-lib反序列化序列化java对象SerializetoBean