如果这个对象使用的不是同一个对象监听器,异步调用。
如果这个对象使用的是同一个对象监听器,同步调用
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离开