月眸


生产者消费者模式代码练习(传统版)

毛毛小妖 2019-08-03 259浏览 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();
		}
	}
}

 

最后修改:2019-08-03 17:35:13 © 著作权归作者所有
如果觉得我的文章对你有用,请随意赞赏
扫一扫支付

上一篇

发表评论

评论列表

还没有人评论哦~赶快抢占沙发吧~