一天一代码 :Java线基础程通信2

一天一代码 :Java线基础程通讯2

001 import java.util.concurrent.locks.* ;
002
003 class ThreadDemo2
004 {
005     public static void main (String[] args)
006     {
007         Resource res = new Resource ();
008
009         Producer pro = new Producer (res);
010         Consumer con = new Consumer (res);
011        
012         Thread t1 =new Thread(pro);
013         Thread t2 =new Thread(pro);
014         Thread t3 =new Thread(con);
015         Thread t4 =new Thread(con);
016
017         t1.start();
018         t2.start();
019         t3.start();
020         t4.start();
021     }
022 }
023
024 class Resource
025 {
026     String name;
027     int count = 1;
028     boolean flag = false;
029     private Lock lock= new ReentrantLock();
030     private Condition condition_pro = lock.newCondition();
031     private Condition condition_con = lock.newCondition();
032
033     public void set(String name)throws InterruptedException
034     {
035         lock.lock();
036         try
037         {
038             while(flag)
039                 condition_pro.await();
040             this.name=name+"......"+count++;
041
042             System.out.println(Thread.currentThread().getName()+"...生产者.."+this.name);
043             flag=true;
044             condition_con.signal();
045         }
046         finally
047         {
048             lock.unlock();
049         }
050
051     }
052
053     public void out()throws InterruptedException
054     {
055         lock.lock();
056         try
057         {
058             while(!flag)
059                 condition_con.await();
060             System.out.println(Thread.currentThread().getName()+"...消费者.."+this.name);
061             flag=false;
062             condition_pro.signal();
063         }
064         finally
065         {
066             lock.unlock();
067         }
068     }
069 }
070
071 class Producer implements Runnable
072 {
073     private Resource res;
074
075     Producer(Resource res)
076     {
077         this.res=res;
078     }
079     public void run()
080     {
081         while(true)
082         {
083             try
084             {
085                 res.set("+商品+");
086             }
087             catch (InterruptedException e)
088             {
089             }
090         }
091     }
092
093 }
094
095 class Consumer implements Runnable
096 {
097     private Resource res;
098
099     Consumer(Resource res)
100     {
101         this.res=res;
102     }
103     public void run()
104     {
105         while(true)
106         {
107             try
108             {
109                 res.out();
110             }
111             catch (InterruptedException e)
112             {
113             }
114         }
115     }
116 }
[/font]