1. 程式人生 > >JAVA中的多線程(六)

JAVA中的多線程(六)

exce pub wait main none int ole ble true

生產者消費者

技術分享
 1 class Resource
 2 {
 3     private String name;
 4     private int count = 1;
 5     private boolean flag = false;
 6     
 7     public synchronized void set(String name)
 8     {
 9         while(flag)
10             try{this.wait();}catch(Exception e){}
11         this.name = name+"--"+count++;
12 System.out.println(Thread.currentThread().getName()+"...生產者..."+this.name); 13 flag = true; 14 this.notifyAll(); 15 } 16 17 public synchronized void out() 18 { 19 while(!flag) 20 try{this.wait();}catch(Exception e){} 21 System.out.println(Thread.currentThread().getName()+"...消費者..."+this
.name); 22 flag = false; 23 this.notifyAll(); 24 } 25 } 26 27 class Producer implements Runnable 28 { 29 private Resource res; 30 31 Producer(Resource res) 32 { 33 this.res = res; 34 } 35 36 public void run() 37 { 38 while(true) 39
{ 40 res.set("+TT+"); 41 } 42 } 43 } 44 45 class Customer implements Runnable 46 { 47 private Resource res; 48 49 Customer(Resource res) 50 { 51 this.res = res; 52 } 53 54 public void run() 55 { 56 while(true) 57 { 58 res.out(); 59 } 60 } 61 } 62 class ProducerCustomerDemo 63 { 64 public static void main(String[] args) 65 { 66 Resource r = new Resource(); 67 68 Producer pro = new Producer(r); 69 Customer con = new Customer(r); 70 71 Thread t1 = new Thread(pro); 72 Thread t2 = new Thread(con); 73 74 t1.start(); 75 t2.start(); 76 } 77 }
View Code

JAVA中的多線程(六)