700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > java多线程之wait和notify协作 生产者和消费者

java多线程之wait和notify协作 生产者和消费者

时间:2021-01-01 14:32:35

相关推荐

java多线程之wait和notify协作 生产者和消费者

这篇直接贴代码了

package cn.javaBase.study_thread1;class Source {public static int num = 0; //假设这是馒头的数量}class Producer implements Runnable {private Object obj;public Producer(Object obj) {this.obj = obj;}@Overridepublic void run() {synchronized (obj) {while (true) {if (Source.num >= 6) { //馒头的数量>=6个的时候,就停下来不生产了,通知别人来消费obj.notify();System.out.println("满了,消费吧");try {obj.wait();} catch (InterruptedException e) {e.printStackTrace();}}Source.num++;System.out.println("已经生产了:"+ Source.num + "个");}}}}class Consumer implements Runnable{private Object obj;public Consumer(Object obj) {this.obj = obj;}@Overridepublic void run() {synchronized (obj) {while (true) {if (Source.num == 0) { //馒头的数量==0个的时候,就停下不消费了,通知别人该生产了obj.notify();System.out.println("没了,生产吧。");try {obj.wait();} catch (InterruptedException e) {e.printStackTrace();}}Source.num--;System.out.println("剩下了:"+ Source.num + "个");}}}}public class MyProducerConsumer {public static void main(String[] args) throws InterruptedException {Object a = new Object();Producer p = new Producer(a);Consumer c = new Consumer(a);new Thread(p).start();Thread.sleep(200); //为了保证先生产,再消费, 不用也可以new Thread(c).start();}}

因为思想跟上一篇的Java多线程之wait和notify:/WNof11020520/p/8780875.html

讲的差不多,所以在这里就不累赘了。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。