- package cn.itcast.gz;
- import java.util.concurrent.locks.Condition;
- import java.util.concurrent.locks.Lock;
- import java.util.concurrent.locks.ReentrantLock;
- /*
- jdk1.5以后将同步和锁封装成了对象。
- 并将操作锁的隐式方式定义到了该对象中,
- 将隐式动作变成了显示动作。
- Lock接口: 出现替代了同步代码块或者同步函数。将同步的隐式锁操作变成现实锁操作。
- 同时更为灵活。可以一个锁上加上多组监视器。
- lock():获取锁。
- unlock():释放锁,通常需要定义finally代码块中。
- Condition接口:出现替代了Object中的wait notify notifyAll方法。
- 将这些监视器方法单独进行了封装,变成Condition监视器对象。
- 可以任意锁进行组合。
- await(); 让线程等待,同时释放锁
- signal(); 唤醒同一把锁中的任意一个等待的线程
- signalAll(); 唤醒同一把锁中的所有等待的线程
- */
- public class ProducerConsumerDemo {
- public static void main(String[] args) {
- Resource4 r = new Resource4();
- Producer producer = new Producer(r);
- Consumer consumer = new Consumer(r);
- Thread t1 = new Thread(producer);
- Thread t2 = new Thread(producer);
- Thread t3 = new Thread(consumer);
- Thread t4 = new Thread(consumer);
- t1.start();
- t2.start();
- t3.start();
- t4.start();
- }
- }
- class Resource4
- {
- Lock lock = new ReentrantLock();
- Condition pro = lock.newCondition();
- Condition con = lock.newCondition();
- private boolean flag= false;
- private int num= 0;
- public void product()
- {
- lock.lock();
- try{
- while(flag)
- try{pro.await();}catch(Exception e){e.printStackTrace();};
- num++;
- System.out.println("生产烤鸭"+num);
- flag = true;
- con.signal();
- }
- finally
- {
- lock.unlock();
- }
- }
- public void consumer()
- {
- lock.lock();
- try
- {
- while(!flag)
- try{con.await();}catch(Exception e){e.printStackTrace();};
- System.out.println("消费烤鸭 "+num);
- flag = false;
- pro.signal();
- }
- finally
- {
- lock.unlock();
- }
- }
- }
- class Producer implements Runnable
- {
- private Resource4 r ;
- public Producer(Resource4 r)
- {
- this.r = r;
- }
- @Override
- public void run() {
- while(true)
- r.product();
- }
- }
- class Consumer implements Runnable
- {
- private Resource4 r;
- public Consumer(Resource4 r)
- {
- this.r = r;
- }
- @Override
- public void run() {
- while(true)
- r.consumer();
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/301220138300.html
来源: http://www.codesnippet.cn/detail/301220138300.html