Object类wait及notify方法原理实例解析
Object类中的wait和notify方法(生产者和消费者模式)不是通过线程调用
- wait():让正在当前对象上活动的线程进入等待状态,无期限等待,直到被唤醒为止
- notify():让正在当前对象上等待的线程唤醒
- notifyAll():唤醒当前对象上处于等待的所有线程
生产者和消费者模式生产线程和消费线程达到均衡
wait方法和notify方法建立在synchronized线程同步的基础之上
- wait方法:释放当前对象占有的锁
- notify方法:通知,不会释放锁
实现生产者和消费者模式仓库容量为10
代码如下
importjava.util.ArrayList; publicclassTest_14{ publicstaticvoidmain(String[]args){ ArrayListlist=newArrayList(); Threadt1=newThread(newProducerThread(list)); t1.setName("producer"); Threadt2=newThread(newConsumerThread(list)); t2.setName("consumer"); t1.start(); t2.start(); } } //生产者线程 classProducerThreadimplementsRunnable{ privateArrayListarrayList; publicProducerThread(ArrayListarrayList){ this.arrayList=arrayList; } @Override publicvoidrun(){ while(true){ synchronized(arrayList){ if(arrayList.size()>9){ try{ arrayList.wait(); }catch(InterruptedExceptione){ e.printStackTrace(); } } try{ Thread.sleep(1000); }catch(InterruptedExceptione){ e.printStackTrace(); } arrayList.add(newObject()); System.out.println(Thread.currentThread().getName()+"--->生产"+"---库存"+arrayList.size()); arrayList.notify(); } } } } //消费者线程 classConsumerThreadimplementsRunnable{ privateArrayListarrayList; publicConsumerThread(ArrayListarrayList){ this.arrayList=arrayList; } @Override publicvoidrun(){ while(true){ synchronized(arrayList){ if(arrayList.size()<9){ try{ arrayList.wait(); }catch(InterruptedExceptione){ e.printStackTrace(); } } try{ Thread.sleep(1000); }catch(InterruptedExceptione){ e.printStackTrace(); } arrayList.remove(0); System.out.println(Thread.currentThread().getName()+"--->消费"+"---库存"+arrayList.size()); arrayList.notify(); } } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。