码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-10-14 13:47:46      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:开关   print   生产者   cat   使用   通讯   runnable   color   ==   

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();
        }
    }
}

 

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

标签:开关   print   生产者   cat   使用   通讯   runnable   color   ==   

原文地址:https://www.cnblogs.com/monkSand/p/9785738.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!