Thread control

public class Buffer {

	int value;
	boolean flag = false;
	
	public synchronized int getValue() {
		if(!flag)
		{
			try{
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		System.out.println("    get_value "+value);
		flag = false;
		notify();
		return value;
	}

	public synchronized void setValue(int value) {
		
		if(flag)
		{
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		System.out.println("set_value "+value);
		this.value = value;
		flag = true;
		notify();
	}
}

猜你喜欢

转载自blog.csdn.net/shadowam/article/details/80177855