下面对synchronized作用于方法进行了测试,从结果可以看出,synchronized作用于方法的时候,锁住的是整个对象,其他的所有的synchronized操作包括获取对象中的属性的的锁的操作都需要等待当前方法执行完毕释放锁之后才能执行,而非synchronized方法则不用等待锁,可以直接执行,这就需要注意没有加同步标志的代码块的线程安全。
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();
}
}