1 package ThreadL; 2 3 import java.util.LinkedList; 4 5 class Queue extends LinkedList<String>{ 6 int lenght; 7 public Queue(){ 8 9 } 10 11 public Queue(int length){ 12 this.lenght = length; 13 } 14 15 public int getLength(){ 16 return this.lenght; 17 } 18 19 public String shift(){ 20 if(!this.isEmpty()){ 21 return this.remove(); 22 }else{ 23 return "空了"; 24 } 25 } 26 27 public void push(String ch){ 28 if(this.size()<=this.lenght){ 29 this.addLast(ch); 30 } 31 } 32 33 public boolean isFull(){ 34 if(this.size() == this.lenght){ 35 return true; 36 }else{ 37 return false; 38 } 39 } 40 } 41 class Depot{ 42 Queue queue = null; 43 public Depot(int length){ 44 this.queue = new Queue(length); 45 } 46 static int i = 1; 47 public synchronized void produce(String ch){ 48 this.notify(); 49 while(this.queue.isFull()){ 50 try { 51 this.wait(); 52 } catch (InterruptedException e) { 53 e.printStackTrace(); 54 } 55 } 56 this.queue.push(ch); 57 System.out.println("生产第\t" + (i++) + "\t个产品\t" + this.queue.getLast()); 58 } 59 public synchronized void consume(){ 60 this.notify(); 61 while(this.queue.isEmpty()){ 62 try { 63 this.wait(); 64 } catch (InterruptedException e) { 65 e.printStackTrace(); 66 } 67 } 68 System.out.println("消耗掉第\t" + (--i) + "\t个产品\t" + this.queue.getFirst()); 69 this.queue.shift(); 70 } 71 } 72 class Produce implements Runnable{ 73 Depot depot; 74 public Produce(Depot depot){ 75 this.depot=depot; 76 } 77 public void run(){ 78 for(int i=0;i<10;i++){ 79 this.depot.produce("A"); 80 } 81 } 82 } 83 class Consume implements Runnable{ 84 Depot depot; 85 public Consume(Depot depot){ 86 this.depot= depot; 87 } 88 public void run(){ 89 for(int i=0;i<10;i++){ 90 this.depot.consume(); 91 } 92 } 93 } 94 public class Thread10 { 95 public static void main(String[] args){ 96 Depot depot = new Depot(8); 97 Thread pro = new Thread(new Produce(depot)); 98 Thread con = new Thread(new Consume(depot)); 99 pro.start(); 100 pro.setName("PRO"); 101 con.start(); 102 con.setName("CON"); 103 } 104 }
时间: 2024-10-16 04:57:27