- 生产者负责生产产品。
- 消费者负责取走并使用产品。
- 生产者生产完成后通知消费者可以取走产品了。
- 消费者消费完产品后需要通知生产者生产产品。
- 生产者没有生产完成,消费者不能取走产品。
- 消费者没有使用完产品,生产者不能生产产品。
1 package Main; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 import java.util.concurrent.Callable; 6 7 class Product 8 { 9 private Object lockObj = new Object(); 10 private String name; 11 private String content; 12 private boolean available = false; 13 14 public void setInfo(String name, String content) 15 { 16 synchronized(this.lockObj) 17 { 18 if(this.available == true) //可以获取 不能生产 19 { 20 try 21 { 22 this.lockObj.wait(); 23 }catch(Exception e) 24 {} 25 } 26 27 28 this.name = name; 29 try 30 { 31 Thread.sleep(200); 32 }catch(Exception ignore) 33 {} 34 35 this.content = content; 36 37 this.available = true;//生产完成 38 this.lockObj.notifyAll(); 39 } 40 } 41 42 public void showInfo() 43 { 44 StringBuffer info = new StringBuffer(); 45 synchronized(this.lockObj) 46 { 47 if(this.available == false) 48 { 49 try 50 { 51 this.lockObj.wait(); 52 }catch(Exception e) 53 {} 54 } 55 info.append("name:").append(this.name); 56 try 57 { 58 Thread.sleep(100); 59 }catch(Exception e) 60 {} 61 info.append(" content:" + this.content); 62 System.out.println(info.toString()); 63 this.available = false; 64 this.lockObj.notifyAll(); 65 } 66 } 67 } 68 69 class Producer implements Runnable 70 { 71 private Product product ; 72 public Producer(Product product) 73 { 74 this.product = product; 75 } 76 77 @Override 78 public void run() 79 { 80 for(int i = 1; i <= 100; i ++) 81 { 82 if(i % 2 ==0) 83 { 84 this.product.setInfo("笔记本", "惠普笔记本,妈妈再也不用担心冬天没暖气了"); 85 }else 86 { 87 this.product.setInfo("Galaxy Note7", "出门旅行,杀人灭口必备武器"); 88 } 89 } 90 } 91 } 92 93 class Consumer implements Runnable 94 { 95 private Product product ; 96 public Consumer(Product product) 97 { 98 this.product = product; 99 } 100 101 @Override 102 public void run() 103 { 104 for(int i =1; i <= 100; i++) 105 { 106 this.product.showInfo(); 107 } 108 } 109 } 110 111 public class Main 112 { 113 public static void main(String[] args) throws Exception 114 { 115 Product product = new Product(); 116 Producer producer = new Producer(product); 117 Consumer consumer = new Consumer(product); 118 Thread tProducer = new Thread(producer); 119 Thread tConsumer = new Thread(consumer); 120 121 tProducer.start(); 122 tConsumer.start(); 123 tProducer.join(); 124 tConsumer.join(); 125 126 System.out.println("Main Done//~~"); 127 } 128 }