標籤:
生產者與消費者:
1 public class ProducerConsumer { 2 public static void main(String[] args) { 3 Basket bs=new Basket(); 4 Producer p=new Producer(bs); 5 Consumer stu1=new Consumer("張東",bs); 6 Consumer stu2=new Consumer("王強",bs); 7 Consumer stu3=new Consumer("趙璐",bs); 8 new Thread(p).start(); 9 new Thread(stu1).start();10 new Thread(stu2).start();11 new Thread(stu3).start();12 }13 }14 15 class ManTou {16 int id;17 ManTou(int id){18 this.id=id;19 }20 public String toString(){21 return "第"+id+"個饅頭" ;22 }23 }24 25 class Basket {26 int index = 0;27 ManTou[] mt = new ManTou[10];28 29 public synchronized void push(ManTou ton) {30 while (index == mt.length) {31 try {32 this.wait();33 } catch (InterruptedException e) {34 e.printStackTrace();35 }36 }37 this.notifyAll();38 mt[index] = ton;39 index++;40 }41 public synchronized ManTou pop() {42 while (index == 0) {43 try {44 this.wait();45 } catch (InterruptedException e) {46 e.printStackTrace();47 }48 }49 this.notifyAll();50 index--;51 return mt[index];52 }53 54 }55 56 class Producer implements Runnable{57 Basket bs= null;58 Producer(Basket bs){59 this.bs=bs;60 }61 public void run(){62 for(int i=1;i<=15;i++){63 ManTou mt=new ManTou(i);64 bs.push(mt);65 System.out.println("李師傅生產了"+mt.toString());66 try{67 Thread.sleep((int)(Math.random()*100));68 }catch(InterruptedException e){69 e.printStackTrace();70 }71 }72 }73 74 }75 76 77 class Consumer implements Runnable{78 Basket bs= null;79 String name;80 Consumer(String stu,Basket bs){81 this.bs=bs;82 name=stu;83 }84 public void run(){85 for(int i=1;i<=5;i++){86 ManTou mt=bs.pop();87 System.out.println(name+"消費了"+mt.toString());88 try{89 Thread.sleep((int)(Math.random()*1000));90 }catch(InterruptedException e){91 e.printStackTrace();92 }93 }94 }95 96 }View Code
JAVA平時練習