下面對synchronized作用于方法進(jìn)行了測試,從結(jié)果可以看出,synchronized作用于方法的時候,鎖住的是整個對象宗挥,其他的所有的synchronized操作包括獲取對象中的屬性的的鎖的操作都需要等待當(dāng)前方法執(zhí)行完畢釋放鎖之后才能執(zhí)行,而非synchronized方法則不用等待鎖种蝶,可以直接執(zhí)行契耿,這就需要注意沒有加同步標(biāo)志的代碼塊的線程安全。
public class synchronizedTest {
private int value=1;
private Integer lo=new Integer("1");
public void A(){
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(df.format(System.currentTimeMillis())+"a:"+value);
value++;
System.out.println(df.format(System.currentTimeMillis())+"a:"+value+" end!");
}
public synchronized void B(){
value++;
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(df.format(System.currentTimeMillis())+"b:"+value);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(df.format(System.currentTimeMillis())+"b:"+value+" end!");
}
public synchronized void C(){
value++;
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(df.format(System.currentTimeMillis())+"c:"+value);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(df.format(System.currentTimeMillis())+"c:"+value+" end!");
}
private synchronized void D(){
synchronized (this){
value++;
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(df.format(System.currentTimeMillis())+"d:"+value);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(df.format(System.currentTimeMillis())+"d:"+value+" end!");
}
}
private synchronized void F(){
synchronized (lo){
value++;
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(df.format(System.currentTimeMillis())+"f:"+value);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(df.format(System.currentTimeMillis())+"f:"+value+" end!");
}
}
public static void main(String[] args){
synchronizedTest test=new synchronizedTest();
Thread B=new Thread(()->{
test.B();
});
Thread C=new Thread(()->{
test.C();
});
Thread D=new Thread(()->{
test.D();
});
Thread F=new Thread(()->{
test.F();
});
B.start();
C.start();
D.start();
F.start();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
test.A();
}
}