多線程學習3-線程互斥與同步通信

1. 線程互斥-synchronized關鍵字

  a.使用於代碼塊上:

    synchronized(監視器對象)

    {

      //code

    }

  b.使用於實例方法上:(監視器對象是this

    public synchronized void ff()

    {

    }

  c.使用於靜態方法上:(監視器對象是字節碼文件,即類名.class

    public static synchronized void ff()

    {

    }

  注意:要想實現互斥,必須保證synchronized的監視器對象相同

 

2.線程同步通信

  需求:子線程循環10次,接着主線程循環100次,再接着子線程循環10次,接着主線程循環100次,如此循環50次。

  思路:將實現循環10次與循環100次的兩個方法,構建於一個類中

  代碼:

class TraditionalThreadCommunicationDemo
{
	public static void main(String [] args)
	{
		final TraditionalThreadCommunicationDemo.Business business = new TraditionalThreadCommunicationDemo().new Business();
		new Thread(new Runnable(){
			@Override
			public void run()
			{
				for(int i=1;i<51;i++)
				{
					business.sub(i);	
				}	
			}
		}).start();
			
		for(int i=1;i<51;i++)
		{
			business.main(i);	
		}		
	}	
	
	class Business
	{
		private boolean flag = false;
		
		public synchronized void sub(int a)
		{
			while(flag) //使用while比if更健壯
			{
				try
				{
					this.wait(); //實現線程通信1
				}
				catch(Exception e)
				{
					e.printStackTrace();
				}
			}
			
			for(int i=1;i<11;i++)
			{
				System.out.println("sub thread sequence of"+i+",loop of"+a);	
			}
			flag = true;
			this.notify(); //實現線程通信2
		}	
		
		public synchronized void main(int a)
		{
			while(!flag)
			{
				try
				{
					this.wait();
				}
				catch(Exception e)
				{
					e.printStackTrace();
				}
			}
			for(int i=1;i<101;i++)
			{
				System.out.println("main thread sequence of"+i+",loop of"+a);	
			}
			flag = false;
			this.notify();
		}	
	}
}


 

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