Lock + Condition(生产者,消费者)

记个代码例子:

1、仓库

package com.zewe.reentrantLock;

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

/**
 * 
 * @author ZeWe
 * 仓库 
 *  
 */
public class Depot {
	
	/*
	 * 最大库存量
	 */
	private int maxSize;
	/*
	 * 现有库存量
	 */
	private int size;
	
	private Lock lock;
	
	private Condition fullCondation;
	
	private Condition emptyCondation;

	public Depot(int maxSize) {
		super();
		this.maxSize = maxSize;
		this.size = 0;
		this.lock = new ReentrantLock();
		this.fullCondation = lock.newCondition();
		this.emptyCondation = lock.newCondition();
	}
	
	public void provider(int nums) {
		
		
		try {
			lock.lock();  // 注意与tryLock 区别 ,lock获取锁失败,等待, tryLock获取锁失败 返回false ,不等待
			int left = nums;
			while(left > 0) {
			    while(size >= maxSize) {
			    	fullCondation.await(); // 已经满了 ,生产等待
			    }
			    int val = (maxSize - size) < left ? (maxSize - size) : left;
			    size+=val;
			    left-=val;
			    System.out.printf("%s provider(%3d) --> left=%3d, val=%3d, size=%3d\n", Thread.currentThread().getName(), nums, left, val, size);
			    emptyCondation.signal();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
		
		
	}
	
	public void consumer(int nums) {
		
		try {
			lock.lock();  
			int left = nums;
			while(left > 0) {
				while(size <= 0) {
					emptyCondation.await(); // 库存为0  消费等待
				}
				int val = size > left ? left : size;
				size-=val;
				left-=val;
			    System.out.printf("%s consumer(%3d) --> left=%3d, val=%3d, size=%3d\n", Thread.currentThread().getName(), nums, left, val, size);
				fullCondation.signal();
			}	
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}

}

2、生产者、消费者

package com.zewe.reentrantLock;
/**
 * 
 * @author ZeWe
 *
 */
public class MainTest {
	
	public static void main(String[] args) {
		
		Depot depot = new Depot(100);
		Provider p = new Provider(depot);
		Consumer c = new Consumer(depot);
		
		c.consumer(150);
		p.provider(50);
		p.provider(100);
		c.consumer(100);
		c.consumer(100);
		p.provider(100);
		p.provider(100);
	}
	
	
	

}

class Provider {
	private Depot depot;
	public Provider(Depot depot) {
		this.depot = depot;
	}
	
	public void provider(int nums) {
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				depot.provider(nums);
			}
		}).start();
	}
	
}	

class Consumer {
	private Depot depot;
	public Consumer(Depot depot) {
		this.depot = depot;
	}
	
	public void consumer(int nums) {
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				depot.consumer(nums);
			}
		}).start();
	}
	
}
发布了73 篇原创文章 · 获赞 78 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/SHIYUN123zw/article/details/91373688
今日推荐