1. 程式人生 > >線程基礎-java

線程基礎-java

線程二 notify method cep 等待 clas sta 修飾 exceptio

1.線程鎖的三種方法,舉例

package cn.itcast.thread.sync;
/**
 * 
 * @author Administrator
 *	對對象的實例加鎖
 */
public class SyncThread implements Runnable {
	
	//創建實例
	static SyncThread instance=new SyncThread();
	static int  i=0;
	
	public void run() {
		// TODO Auto-generated method stub
		for (int j = 0; j < 100000; j++) {
			
			
			/*
			 * 
			 * 方法一:
			 * synchronized (instance) {
				i++;
			}*/
			//對方法上鎖
			increase();
		}
	}
	
	//方法二:加在方法上,如果不是static修飾的 ,要確保是同一個鎖才能保證同步的進行,用static修飾的是方法三
		private synchronized void increase() {
			// TODO Auto-generated method stub
			i++;	//對成員變量的操作要加上鎖
			System.out.println(Thread.currentThread().getName()+"----------------"+i);
		}
		
	public static void main(String[] args) {
		Thread t1=new Thread(instance);
		Thread t2=new Thread(instance);
		Thread t3=new Thread(instance);

		t1.start();t2.start();t3.start();
		try {
			t1.join();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("-----------最後的結果:"+i);
		
	}
	
}

 2.object.wait()

  

//代碼需要寫在鎖中
//線程一
 synchronized(object){  //鎖既是監聽器

       object.wait();  //此句會使得當前線程等待,且釋放監視器的所有權,等待被其他線程喚醒且釋放了monitor之後
        
}

//線程二:
synchronized(object){  //鎖既是監聽器

       object.notify();  //此句會喚醒一個等待的線程,
        
}

  

線程基礎-java