1. 程式人生 > 其它 >簡單的生產者與消費者程式碼

簡單的生產者與消費者程式碼

 1 package com.producerandconsumer;
 2 
 3 class Message2{
 4 private String name;
 5 private String deString;
 6 private boolean tag = true;
 7 public synchronized void setInf(String name,String deString) {
 8 if (!this.tag){//消費者未消費
 9 try {
10 super.wait();
11 } catch (InterruptedException e) {
12 // TODO Auto-generated catch block
13 e.printStackTrace(); 14 } 15 } 16 this.name = name; 17 this.deString = deString; 18 this.tag = false; 19 super.notify(); 20 } 21 public synchronized void getInf() { 22 if (this.tag) {//生產者未生產 23 try { 24 super.wait(); 25 } catch (InterruptedException e) { 26 // TODO Auto-generated catch block 27 e.printStackTrace();
28 } 29 } 30 try{ 31 System.out.println(this.name + " 是一個 " + this.deString + " 的人;" + Thread.currentThread().getName()); 32 }finally { 33 this.tag = true; 34 super.notify(); 35 } 36 } 37 } 38 class Producer1 implements Runnable{ 39 private Message2 msg; 40 public Producer1(Message2 msg) { 41 // TODO Auto-generated constructor stub
42 this.msg = msg; 43 } 44 @Override 45 public void run() { 46 // TODO Auto-generated method stub 47 for (int i = 0; i < 100; i++) { 48 if (i%2 == 0) { 49 msg.setInf("王強", "樂觀的"); 50 }else msg.setInf("張三", "自信的"); 51 try { 52 Thread.sleep(1000); 53 } catch (InterruptedException e) { 54 // TODO Auto-generated catch block 55 e.printStackTrace(); 56 } 57 } 58 } 59 } 60 class Cusumer2 implements Runnable{ 61 private Message2 msg; 62 public Cusumer2(Message2 msg) { 63 // TODO Auto-generated constructor stub 64 this.msg = msg; 65 } 66 @Override 67 public void run() { 68 // TODO Auto-generated method stub 69 for (int i = 0 ;i < 100;i++){ 70 try { 71 Thread.sleep(1000); 72 } catch (InterruptedException e) { 73 // TODO Auto-generated catch block 74 e.printStackTrace(); 75 } 76 msg.getInf(); 77 } 78 } 79 80 } 81 public class ProducerAndConsumerTest2 { 82 83 @SuppressWarnings("unused") 84 public static void main(String[] args) { 85 // TODO Auto-generated method stub 86 Message2 message2 = new Message2(); 87 new Thread(new Producer1(message2),"生產者").start(); 88 new Thread(new Cusumer2(message2),"消費者").start(); 89 } 90 91 }
View Code

學到了:wait()和notify() notifyALL()必須放在synchronized程式碼塊裡或者方法塊裡