黑马程序员技术交流社区

标题: 生产者消费者问题 [打印本页]

作者: guohaichang    时间: 2015-6-21 21:54
标题: 生产者消费者问题
谁能说明一下这个Lock类,还有ReentrantLock类?

import java.util.concurrent.locks.*;

class Resource {
        private String name;
        private int count = 1;
        private boolean flg = false; //true时有货,可以消费。
       
        Lock lock = new ReentrantLock();
       
        Condition conditionPro = lock.newCondition();//用来控制生产者线程唤醒或等待
        Condition conditionCon = lock.newCondition();//用来控制消费者线程唤醒或等待
       
        public void setProducer(String name) throws InterruptedException{
                lock.lock();
                try {
                        while(flg) {
                                conditionPro.await();
                        }
                        this.name = name + "..." + count++;
                        System.out.println(Thread.currentThread().getName() + "...生产..." + this.name);
                        flg = true;
                        conditionCon.signal();
                } finally {
                        lock.unlock();
                }
        }
       
        public void getConsumer() throws InterruptedException {
                lock.lock();
                try {
                        while(!flg) {
                                conditionCon.await();
                        }
                        System.out.println(Thread.currentThread().getName() + "...消费..." + this.name);
                        flg = false;
                        conditionPro.signal();
                } finally {
                        lock.unlock();
                }
        }
}

class Producer  implements Runnable {
        private Resource res = new Resource();
        Producer(Resource res) {
                this.res = res;
        }
        public void run() {
                while(true) {
                        try {
                                res.setProducer("蛋糕");       
                        } catch(InterruptedException ie) {
                               
                        }
                }
        }
}

class Consumer implements Runnable {
        private Resource res = new Resource();
        Consumer(Resource res) {
                this.res = res;
        }
        public void run() {
                while(true) {
                        try {
                                res.getConsumer();
                        } catch(InterruptedException ie) {
                               
                        }
                }
        }
}

class Test {
        public static void main(String args[]) {
                Resource res = new Resource();
               
                new Thread(new Producer(res),"1").start();
                new Thread(new Consumer(res),"2").start();
                new Thread(new Consumer(res),"3").start();
        }
}






欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2