本帖最后由 巩建 于 2013-6-18 20:43 编辑
- <p><strong><font color="lime">//这里为什么没有东西输出呢? 错误在哪里 求解释?</font></strong></p><p>package com.heima.exercise;
- import java.util.concurrent.locks.Condition;
- import java.util.concurrent.locks.Lock;
- import java.util.concurrent.locks.ReentrantLock;
- //资源
- class Resource1{
- private String name;
- boolean flag=false;
- private Lock lock=new ReentrantLock();
- private Condition pre_condition =lock.newCondition();
- private Condition cus_condition=lock.newCondition();
- //生产者的方法
- public void set(String name) throws Exception{
- lock.lock();
- try{
- while(flag){
- pre_condition.await();
- this.name=name;
- System.out.println(Thread.currentThread().getName()+"生产者:"+this.name);
- this.flag=true;
- cus_condition.signal();
- }
- }finally{lock.unlock();}
- }
- //消费者的方法
- public void out() throws Exception{
- try{
- lock.lock();
- while(!flag){
- cus_condition.await();
- System.out.println(Thread.currentThread().getName()+"消费者:"+this.name);
- this.flag=false;
- pre_condition.signal();
- }
- }finally{lock.unlock();}
- }
- }
- //生产者
- class Producer implements Runnable{
- private Resource1 r;
- public Producer(Resource1 r) {
- this.r=r;
- }
- public void run() {
- while(true){
- try {r.set("营养品");} catch (Exception e) {e.printStackTrace();}
- }
- }
- }
- //消费者
- class Customer implements Runnable{
- private Resource1 r;
- public Customer(Resource1 r){
- this.r=r;
- }
- public void run() {
- while(true){
- try {r.out();} catch (Exception e) {e.printStackTrace();}
- }
- }
- }
- public class NewDemo {
- public static void main(String[] args) {
- Resource1 r=new Resource1();
- Producer p=new Producer(r);
- Customer c=new Customer(r);
- Thread t1=new Thread(p);
- Thread t2=new Thread(p);
- Thread t3=new Thread(c);
- Thread t4=new Thread(c);
- t1.start();
- t2.start();
- t3.start();
- t4.start();
- }
- }
- </p>
复制代码 |