Java Lock Condition 生产者消费者模式示例

package test;

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

public class LockTest {
	public static void main(String[] args) {
		//创建需要生产的资源类
		Resources r = new Resources("水煮鱼");
		//创建两个生产者任务线程
		Pro p1 = new Pro(r);
		Pro p2 = new Pro(r);
		Thread t1 = new Thread(p1);
		Thread t2 = new Thread(p2);
		//创建两个消费者任务线程
		Cus c1 = new Cus(r);
		Cus c2 = new Cus(r);
		Thread t3 = new Thread(c1);
		Thread t4 = new Thread(c2);
		
		//开启生产和消费线程
		t1.start();
		t2.start();
		t3.start();
		t4.start();
	}
}
//生产者任务
class Pro implements Runnable{
	private Resources res;
	public Pro(Resources res){
		this.res = res;
	}
	@Override
	public void run() {
		try {
			res.shengChan();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
//消费者任务
class Cus implements Runnable{
	private Resources res;
	public Cus(Resources res){
		this.res = res;
	}
	@Override
	public void run() {
		try {
			res.xiaoFei();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
//资源类
class Resources{
	private String name;
	private int count = 1;
	private boolean flag = false;
	private Lock lock = new ReentrantLock();
	private Condition scCon = lock.newCondition();
	private Condition xfCon = lock.newCondition();
	public Resources(String name){
		this.name = name;
	}
	//生产
	public void shengChan() throws InterruptedException{
		while(true){
			lock.lock();
			try{
				while(flag){
					scCon.await();
				}
				System.out.println("生产者---:" + name + count);
				count ++;
				flag = true;
				xfCon.signal();
			}finally{
				lock.unlock();
			}
		}
	}
	//消费
	public void xiaoFei() throws InterruptedException{
		while(true){
			lock.lock();
			try{
				while(!flag)
					xfCon.await();
				System.out.println("消费者---:" + name + count);
				flag = false;
				scCon.signal();
			}finally{
				lock.unlock();
			}
		}
	}
}

 

你可能感兴趣的:(锁,同步,多线程)