Synchronized(非this對象)

如果這個對象使用的不是同一個對象監聽器,異步調用。

如果這個對象使用的是同一個對象監聽器,同步調用

 

public class service {

	private String usernameParam;
	private String passwordParam;
	private String anyString=new String();
	
	public void setUsernamePassword(String username,String password) {
		try {
			synchronized (anyString) {
				System.out.println("線程名稱爲"+Thread.currentThread().getName()+"在"+System.currentTimeMillis()+"進入同步快");
				usernameParam=username;
				Thread.sleep(3000);
				passwordParam=password;
				System.out.println("線程名稱爲"+Thread.currentThread().getName()+"在"+System.currentTimeMillis()+"離開同步快");
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}



兩個線程同時調用,爲同一個對象監聽器,同步調用
輸出結果:A進入 A離開 B進入 B離開
public class service {

	private String usernameParam;
	private String passwordParam;
	
	public void setUsernamePassword(String username,String password) {
		try {
			String anyString=new String();
			synchronized (anyString) {
				System.out.println("線程名稱爲"+Thread.currentThread().getName()+"在"+System.currentTimeMillis()+"進入同步快");
				usernameParam=username;
				Thread.sleep(3000);
				passwordParam=password;
				System.out.println("線程名稱爲"+Thread.currentThread().getName()+"在"+System.currentTimeMillis()+"離開同步快");
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}


兩個線程同時調用,不同的對象監聽器,異步
輸出結果:A進入 B進入 A離開 B離開

 

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