A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© guohaichang 中级黑马   /  2015-6-21 21:54  /  285 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

谁能说明一下这个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();
        }
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马