标签:package import public 多线程 蜂蜜
1.蜜蜂和熊的生产消费关系,熊在蜂蜜满10斤吃掉。蜜蜂一次生产一斤蜂蜜,且蜜蜂生成一斤蜂蜜花费的时间是10s。
十只蜜蜂和两只熊。
package com.yehomlab; import java.util.ArrayList; import java.util.List; class Bear implements Runnable { List<Integer> list; public Bear(List<Integer> list){ this.list=list; } public void run() { while(true){ synchronized(list){ int size=list.size(); if(size==0){ try { System.out.println("没蜜了快点采蜜去!"); list.wait(); } catch (Exception e) { } } else if(size>0 && size<10){ try { System.out.println("装满十个我再吃"); list.wait(); } catch (Exception e) { } } else if(size==10){ Integer i=list.remove(0); System.out.println("吃蜜喽"); list.notifyAll(); } } //yield(); } } } class Bee implements Runnable { final static int MAX=10; List<Integer> list; public Bee(List<Integer> list){ this.list=list; } public void run() { int i=1; while(true){ synchronized (list) { int size=list.size(); if(size>=MAX){ try { list.wait(); } catch (Exception e) { } } else if(size<MAX){ list.add(new Integer(i)); System.out.println("正在生产花蜜"); try { Thread.sleep(200); } catch (Exception e) { } i+=1; list.notifyAll(); } } } } } public class BeeBearDemo { public static void main(String[] args){ List<Integer> list =new ArrayList<Integer>(); Bear B1 = new Bear(list); Bear B2 = new Bear(list); Bee E1 = new Bee(list); Bee E2 = new Bee(list); Bee E3 = new Bee(list); Bee E4 = new Bee(list); Bee E5 = new Bee(list); Bee E6 = new Bee(list); Bee E7 = new Bee(list); Bee E8 = new Bee(list); Bee E9 = new Bee(list); Bee E10= new Bee(list); new Thread(B1).start(); new Thread(B2).start(); new Thread(E1).start(); new Thread(E2).start(); new Thread(E3).start(); new Thread(E4).start(); new Thread(E5).start(); new Thread(E6).start(); new Thread(E7).start(); new Thread(E8).start(); new Thread(E9).start(); new Thread(E10).start(); } }
本文出自 “yehomlab” 博客,转载请与作者联系!
标签:package import public 多线程 蜂蜜
原文地址:http://yehom.blog.51cto.com/5159116/1784268