生产者消费者模式代码练习(传统版)
网站首页 文章专栏 生产者消费者模式代码练习(传统版)
生产者消费者模式代码练习(传统版)
编辑时间:2019-08-03 17:36 作者:毛毛小妖 浏览量:50 评论数:0

利用Lock和Condition实现 

package com.sy.blockingQueue;

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

class ShareResource{
	private int number=0;
	private Lock lock = new ReentrantLock();
	Condition condition = lock.newCondition();
	
	public void inCrement() throws InterruptedException{
		try {
			lock.lock();
			while(number != 0){
				condition.await();
			}
			number ++;
			System.out.println(Thread.currentThread().getName()+"\t"+number);
			condition.signalAll();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			lock.unlock();
		}
	}
	
	public void deCrement() throws InterruptedException{
		try {
			lock.lock();
			while(number != 1){
				condition.await();
			}
			number --;
			System.out.println(Thread.currentThread().getName()+"\t"+number);
			condition.signalAll();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			lock.unlock();
		}
	}
}

public class TraditionalProducerConsumer {
	public static void main(String[] args) {
		ShareResource resource = new ShareResource();
		
		for(int i=0;i<5;i++){
			new Thread(()->{
				try {
					resource.inCrement();
				} catch (Exception e) {
					e.printStackTrace();
				}
			},"A").start();
		}
		
		for(int i=0;i<5;i++){
			new Thread(()->{
				try {
					resource.deCrement();
				} catch (Exception e) {
					e.printStackTrace();
				}
			},"B").start();
		}
	}
}

 

推荐文章
来说两句吧
最新评论
    还没有人评论哦,快来坐沙发吧!