这是一个生产者与消费者的例子。 关于catch的使用,为什么不在1和2处处理异常,而要在3和4处处理异常。 这种处理方式的目的和意义什么?
importjava.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; importjava.util.concurrent.locks.ReentrantLock; public class ProducerConsumerDemo { publicstatic void main(String[] args) { Resourcer = new Resource(); Producerpro= new Producer(r); Consumercon= new Consumer(r); newThread(pro).start(); newThread(pro).start(); newThread(con).start(); newThread(con).start(); } } class Resource { privateString name; privateint count = 1; privateboolean flag = false; privateLock lock = new ReentrantLock(); privateCondition pro_condition = lock.newCondition(); privateCondition con_condition = lock.newCondition(); publicvoid set(String name) throws InterruptedException { lock.lock(); try{ while(flag) pro_condition.await(); this.name= name + "-" + count++; System.out.println(Thread.currentThread().getName()+ "...生产者。。。" +this.name); flag= true; con_condition.signal(); }//① finally { lock.unlock(); } } publicvoid out() throws InterruptedException { lock.lock(); try{ while(!flag) con_condition.await(); System.out.println(Thread.currentThread().getName()+ "。。。...消费者。。." +this.name); flag= false; pro_condition.signal(); }//② finally { lock.unlock(); } } } class Producer implements Runnable { publicProducer(Resource r) { super(); this.r= r; } privateResource r; publicvoid run() { while(true) { try{ r.set("+商品+"); }catch (InterruptedException e) {//③ //TODO Auto-generated catch block e.printStackTrace(); } } } } class Consumer implements Runnable { privateResource r; publicConsumer(Resource r) { super(); this.r= r; } publicvoid run() { while(true) { try{ r.out(); }catch (InterruptedException e) {//④ //TODO Auto-generated catch block e.printStackTrace(); } } } }
|