- import java.util.concurrent.locks.*;
- class Resource{
- private String name;
- private int count = 1;
- private boolean flag = false;
- //创建一个锁对象
- Lock lock = new ReentrantLock();
- //通过已有的锁获取该锁上的监视器对象
- Condition con = lock.newCondition();
- public void set(String name){
- lock.lock();
- try{
- while(flag) //重复判断生产者是否生产
- try{
- con.await();//生产者等待
- }catch(InterruptedException e){
- e.printStackTrace();
- }
- this.name = name + count;
- count++;
- System.out.println(Thread.currentThread().getName()+"...生产者..."+this.name);
- flag = true;
- con.signalAll();//唤醒消费者
- }finally{
- lock.unlock();//解锁
- }
- }
- public void out(){
- lock.lock();
- try{
- while(!flag) //重复判断是否可以消费
- try{
- con.await();//消费者等待
- }catch(InterruptedException e){
- e.printStackTrace();
- }
- System.out.println(Thread.currentThread().getName()+"...消费者..."+this.name);
- flag = false;
- con.signalAll();//唤醒生产者
- }finally{
- lock.unlock();//解锁
- }
- }
- }
- //生产者
- class Producer implements Runnable{
- private Resource r;
- Producer(Resource r){
- this.r = r;
- }
- //复写run()
- public void run(){
- while(true){
- r.set("Item");
- }
- }
- }
- //消费者
- class Consumer implements Runnable{
- private Resource r;
- Consumer(Resource r){
- this.r = r;
- }
- //复写run()
- public void run(){
- while(true){
- r.out();
- }
- }
- }
- public class ResourceDemo {
- public static void main(String[] args){
- Resource r = new Resource();
- Producer pro = new Producer(r);
- Consumer con = new Consumer(r);
- Thread t0 = new Thread(pro); //生产者线程t0
- Thread t1 = new Thread(pro); //生产者线程t1
- Thread t2 = new Thread(con); //消费者线程t2
- Thread t3 = new Thread(con); //消费者线程t3
- t0.start();
- t1.start();
- t2.start();
- t3.start();
- }
- }
复制代码
|
|