Object类wait及notify方法的案例分析
小编给大家分享一下Object类wait及notify方法的案例分析,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨吧!
Object类中的wait和notify方法(生产者和消费者模式) 不是通过线程调用
wait(): 让正在当前对象上活动的线程进入等待状态,无期限等待,直到被唤醒为止notify(): 让正在当前对象上等待的线程唤醒notifyAll(): 唤醒当前对象上处于等待的所有线程生产者和消费者模式 生产线程和消费线程达到均衡
wait方法和notify方法建立在synchronized线程同步的基础之上
wait方法: 释放当前对象占有的锁notify方法: 通知,不会释放锁实现生产者和消费者模式 仓库容量为10
代码如下
import java.util.ArrayList;public class Test_14 { public static void main(String[] args) { ArrayList list = new ArrayList(); Thread t1 = new Thread(new ProducerThread(list)); t1.setName("producer"); Thread t2 = new Thread(new ConsumerThread(list)); t2.setName("consumer"); t1.start(); t2.start(); }}//生产者线程class ProducerThread implements Runnable{ private ArrayList arrayList; public ProducerThread(ArrayList arrayList) { this.arrayList = arrayList; } @Override public void run() { while (true) { synchronized (arrayList) { if (arrayList.size() > 9){ try { arrayList.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } arrayList.add(new Object()); System.out.println(Thread.currentThread().getName() + "---> 生产" + "---库存" + arrayList.size()); arrayList.notify(); } } }}//消费者线程class ConsumerThread implements Runnable{ private ArrayList arrayList; public ConsumerThread(ArrayList arrayList) { this.arrayList = arrayList; } @Override public void run() { while (true){ synchronized (arrayList){ if (arrayList.size() < 9){ try { arrayList.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } arrayList.remove(0); System.out.println(Thread.currentThread().getName() + "---> 消费" + "---库存" + arrayList.size()); arrayList.notify(); } } }}
看完了这篇文章,相信你对Object类wait及notify方法的案例分析有了一定的了解,想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。