如果這個對象使用的不是同一個對象監聽器,異步調用。
如果這個對象使用的是同一個對象監聽器,同步調用
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離開