多線程-等待喚醒機制-代碼優化

class Resource{
	//屬性進行私有化,對外提供get方法
	private String name;
	private String sex;
	private boolean flag = false;
	
	public synchronized void set(String name,String sex){//使用同步函數
	if(flag){
		try{
			this.wait();
		}
		catch(InterruptedException e){
			
		}
	}
	
	this.name = name;//要同步的代碼變成了這兩句話了,當然還有下面的依據輸出語句
	this.sex = sex;
	
	flag = true;
	this.notify();
	}
	
	public synchronized void out(){
		if(!flag){
			try{
				this.wait();
			}
			catch(InterruptedException e){
				
			}
		}
		
		System.out.println(name+"..."+sex);
		
		flag = false;
		this.notify();
	}
}

class Input implements Runnable{
	Resource r;
	Input(Resource r){
		this.r = r;
	}
	
	public void run(){
		int x = 0;
		while(true){	
			if(x == 0){
				r.set("zhangsan","man");
			}
			else{
				r.set("麗麗","女");
			}
		
			x = (x + 1)%2;
		}
	}
}

class Output implements Runnable{
	Resource r;
	Output(Resource r){
		this.r = r;
	}
	
	public void run(){
		while(true){
			r.out();
		}
	}
}

class Test{
	public static void main(String [] args){
		Resource r = new Resource();
		
		Input in = new Input(r);
		Output out = new Output(r);
		
		Thread t1 = new Thread(in);
		Thread t2 = new Thread(out);
		
		t1.start();
		t2.start();
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章