Java線程互斥(三)

package wo;

public class En extends Thread{
	public En(String name)
	{
		super(name);
	}
	private static int count=0;
	private static boolean flag=true;
	
	public synchronized void run()
	{
		int i;
		for(i=0;i<30;i++){
			if(!flag)
				try{
					wait();
				}catch(InterruptedException e){}
				flag=false;
				count=count+1;
				flag=true;
				notifyAll();
				System.out.println("Myname is:"+getName()+"  count="+count);
				try{
					this.sleep(10);
				}catch(InterruptedException e){}
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		En t1=new En("First Thread");
		En t2=new En("Second Thread");
		En t3=new En("Third Thread");
		t1.start();
		t2.start();
		t3.start();

	}

}

 
發佈了36 篇原創文章 · 獲贊 0 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章