java使用lock实现一个简单的生产者和消费者模式

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Five {
    public static void main(String[] args) {
        final Service myService = new Service();
        for(int i = 0 ; i < 10 ; i ++){
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    while(true){
                        myService.push();
                    }
                }
            });
            thread.start();
        }
        for(int i = 0 ; i < 10 ; i ++){
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    while(true){
                        myService.pop();
                    }
                }
            });
            thread.start();
        }
    }
}


class Service{
    //创建锁
    private ReentrantLock lock = new ReentrantLock();
    //创建通讯器
    private Condition condition = lock.newCondition();
    //创建一个开关
    private boolean off = false;
    
    public void push(){
        try {
            lock.lock();
            if(off == false) condition.wait();
            System.out.println("生产!");
            off = false;
            condition.signalAll();
        } catch (Exception e) {
            // TODO: handle exception
        }finally {
            lock.unlock();
        }
    }
    public void pop(){
        try {
            lock.lock();
            if(off == true) condition.wait();
            System.out.println("消费!");
            off = true;
            condition.signalAll();
        } catch (Exception e) {
            // TODO: handle exception
        }finally {
            lock.unlock();
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/monkSand/p/9785738.html