收藏 分销(赏)

生产者-消费者-停止生产-停止消费.doc

上传人:仙人****88 文档编号:9345456 上传时间:2025-03-23 格式:DOC 页数:4 大小:42.54KB
下载 相关 举报
生产者-消费者-停止生产-停止消费.doc_第1页
第1页 / 共4页
生产者-消费者-停止生产-停止消费.doc_第2页
第2页 / 共4页
点击查看更多>>
资源描述
命题:生产者,消费者; 1. 当商品到达10个,则停止生产; 2. 当商品为0时,则停止生产, 产品集: Products package RunnableTest.Test2; import java.util.Stack; public class Products { int counter = 0; Stack stack; public Products() { stack = new Stack(); } public synchronized void get() { int item = stack.size() ; if(item == 0) { try { System.out.println("暂停消费"); wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } Object getS = stack.pop(); System.out.println("消费 "+getS); this.notify(); } public synchronized void put() { int item = stack.size()+1 ; if(item>=10) { try { System.out.println("暂停生产 "); wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } counter ++; stack.push(item); System.out.println("共生产 "+counter+";生产 "+item); this.notify(); } } 生产者: Produce package RunnableTest.Test2; public class Produce implements Runnable{ Products products; public Produce(Products p) { products = p; } @Override public void run() { // TODO Auto-generated method stub while(true) { try { Thread.sleep((int)Math.random()*1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } products.put(); } } } 消费者: Customer package RunnableTest.Test2; public class Customer implements Runnable{ Products products; public Customer(Products p) { products = p; } @Override public void run() { // TODO Auto-generated method stub while(true) { try { Thread.sleep((int)Math.random()*900); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } products.get(); } } } 测试:Test2 package RunnableTest.Test2; public class Test2 { public static void main(String[] args) { Products p =new Products();//产品集 Produce produce =new Produce(p);//生产 new Thread(produce).start(); Customer customer =new Customer(p);//消费 Thread t = new Thread(customer); t.start(); } } ==部分结果== 共生产 1;生产 1 消费 1 暂停消费 共生产 2;生产 1 消费 1 暂停消费 共生产 3;生产 1 消费 1 共生产 4;生产 1 消费 1 共生产 5;生产 1 消费 1 共生产 6;生产 1 消费 1 ……………… ………………. 共生产 9406;生产 5 共生产 9407;生产 6 共生产 9408;生产 7 共生产 9409;生产 8 共生产 9410;生产 9 暂停生产 消费 9 共生产 9411;生产 10 暂停生产 消费 10 共生产 9412;生产 10 暂停生产 消费 10
展开阅读全文

开通  VIP会员、SVIP会员  优惠大
下载10份以上建议开通VIP会员
下载20份以上建议开通SVIP会员


开通VIP      成为共赢上传
相似文档                                   自信AI助手自信AI助手

当前位置:首页 > 教育专区 > 小学其他

移动网页_全站_页脚广告1

关于我们      便捷服务       自信AI       AI导航        抽奖活动

©2010-2025 宁波自信网络信息技术有限公司  版权所有

客服电话:4009-655-100  投诉/维权电话:18658249818

gongan.png浙公网安备33021202000488号   

icp.png浙ICP备2021020529号-1  |  浙B2-20240490  

关注我们 :微信公众号    抖音    微博    LOFTER 

客服