java 条件变量Condition——笔记


package com.warehorseCondition;

public class GetThread implements Runnable{

	private WareHorse horse;
	
	public GetThread(WareHorse horse) {
		super();
		this.horse = horse;
	}

	@Override
	public void run() {
		while(true){
			horse.get();
		}
	}

	
}


package com.warehorseCondition;

public class PutThread implements Runnable{

	private WareHorse horse;

	public PutThread(WareHorse horse) {
		super();
		this.horse = horse;
	}

	@Override
	public void run() {
		while(true){
			horse.put();
		}
	}
	
}



package com.warehorseCondition;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;


public class WareHorse {

	//仓库是否放满
	private boolean isFull = false;

	//重入锁
	private ReentrantLock lock = new ReentrantLock();
	
	//条件变量      未满
	private Condition notFull = lock.newCondition();
	
	//条件变量      不空
	private Condition notEmpty = lock.newCondition();
	
	
	public void get(){
		
		//让put获得锁
		lock.lock();
		
		if(isFull){
			System.out.println("放满,来取吧!");
			//isFull变为false,表示已空
			isFull = !isFull;
			notFull.signal();
			lock.unlock();
		}else{
			try {
				notEmpty.await();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public void put(){
		lock.lock();
		if(!isFull){
			System.out.println("已空,请放!");
			//isFull变为true,表示已满
			isFull = !isFull;
			notEmpty.signal();
		}else{
			try {
				notFull.await();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
} 



package com.warehorseCondition;

public class WareHorseTest {

	public static void main(String[] args) {
		WareHorse horse = new WareHorse();
		PutThread p = new PutThread(horse);
		GetThread g = new GetThread(horse);
		new Thread(p).start();
		new Thread(g).start();
	}
}


你可能感兴趣的:(Java多线程)