第一種:package?com.ucmed.zsyy.util;
/**
*?Created?by?ucmed?on?2017/2/8.
*/
public?class?DirtyRead?{
private?String?username?=?"zjkj";
private?String?password?=?"123";
public?synchronized?void?setValue(String?username,?String?password)?{
System.out.println("set線程:"?+?Thread.currentThread().getPriority());
this.username?=?username;
try?{
Thread.sleep(2000);
}?catch(InterruptedException?e)?{
e.printStackTrace();
}
this.password?=?password;
System.out.println("setValue最終結果:username?=?"?+?username?+?"??,?password?=?"?+?password);
}
public?void?getValue()?{
System.out.println("get線程:"?+?Thread.currentThread().getPriority());
System.out.println("getValue最終結果:username?=?"?+?username?+?"??,?password?=?"?+?password);
}
public?static?void?main(String[]?args)?throws?InterruptedException?{
final?DirtyRead?dr?=?new?DirtyRead();
Thread?t1?=?new?Thread(new?Runnable()?{
@Override
public?void?run()?{
dr.setValue("z3",?"456");
}
});
System.out.println("主線程:"?+?Thread.currentThread().getPriority());
t1.start();
Thread.sleep(1000);
dr.getValue();
}
}
第二種:
package?com.ucmed.zsyy.util;
/**
*?Created?by?ucmed?on?2017/2/8.
*/
public?class?DirtyRead?{
private?String?username?=?"zjkj";
private?String?password?=?"123";
public?synchronized?void?setValue(String?username,?String?password)?{
System.out.println("set線程:"?+?Thread.currentThread().getPriority());
this.username?=?username;
try?{
Thread.sleep(2000);
}?catch(InterruptedException?e)?{
e.printStackTrace();
}
this.password?=?password;
System.out.println("setValue最終結果:username?=?"?+?username?+?"??,?password?=?"?+?password);
}
public?synchronized?void?getValue()?{
System.out.println("get線程:"?+?Thread.currentThread().getPriority());
System.out.println("getValue最終結果:username?=?"?+?username?+?"??,?password?=?"?+?password);
}
public?static?void?main(String[]?args)?throws?InterruptedException?{
final?DirtyRead?dr?=?new?DirtyRead();
Thread?t1?=?new?Thread(new?Runnable()?{
@Override
public?void?run()?{
dr.setValue("z3",?"456");
}
});
System.out.println("主線程:"?+?Thread.currentThread().getPriority());
t1.start();
Thread.sleep(1000);
dr.getValue();
}
}
理解:
這里只有一個對象,一個對象的多個synchronized修飾的方法的情況
上面例子是當get方法加上鎖后,要等待set方法執行完后再執行
在方法上加synchronized關鍵字,持有的鎖為當前對象,當一個線程調用了其中一個synchronized的方法后,其他線程再調用該類中其他synchronized修飾的方法會掛起等待,需要等上一個線程執行完,釋放鎖后,其他調用線程取得鎖后才會執行
不是多個鎖,是多個synchronized修飾的方法..這些方法是同一個鎖