看到网上很多资料都讲解synchronized的用法详解,确实有很多的知识点,但初学者可能看的比较头晕,这里浅谈下很重要的synchronized修饰普通方法和修饰静态方法,也是在实际开发中用的比较多的。
这里先说synchronized修饰普通方法,修饰代码块和修饰静态方法的最大特点:
修饰普通方法,修饰代码块:只针对调用它的对象起作用。
修饰静态方法:针对该类的所有对象都起作用。
直接上代码:
public class SyncTest {
public void test1(){
synchronized (this){
for (int i = 0; i < 10; i++) {
log.info("test1 - {}",i);
}
}
}
public synchronized void test2(){
for (int i = 0; i < 10; i++) {
log.info("test2 - {}",i);
}
}
public static void main(String[] args) {
SyncTest syncTest1 = new SyncTest();
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(() ->{
syncTest1.test1();
});
executorService.execute(() ->{
syncTest1.test1();
});
}
}
输出结果:
可以看出,两个线程很好的保持了同步,达到了线程安全的效果,
出现这个的原因是:在test1方法中,我们使用同一个对象调用它,所以每个线程都要依次获得该对象的锁才能执行,这里注意的是,起作用的是该对象(同一个),下面调用test2方法结果也一致,因为执行代码都在synchronized里被修饰了。
但是如果我们新增加一个对象,分别调用自己的test1方法,如下:
SyncTest syncTest1 = new SyncTest();
SyncTest syncTest2 = new SyncTest();
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(() ->{
syncTest1.test2();
});
executorService.execute(() ->{
syncTest2.test2();
});
结果:
可以看到,结果是线程不同步的,这是因为用synchronized修饰的只对当前对象起作用,而对其他对象的synchronized所针对的对象是不干扰的。
下面来看调用静态方法会出现什么结果:
public class SyncTest {
public void test1(){
synchronized (this){
for (int i = 0; i < 10; i++) {
log.info("test1 - {}",i);
}
}
}
public synchronized static void test2(){ //改为静态方法
for (int i = 0; i < 10; i++) {
log.info("test2 - {}",i);
}
}
public static void main(String[] args) {
SyncTest syncTest1 = new SyncTest();
SyncTest syncTest2 = new SyncTest();
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(() ->{
syncTest1.test2();
});
executorService.execute(() ->{
syncTest2.test2();
});
}
}
我们将test2方法改为静态方法,也是创建两个对象,调用自己的test2方法,结果如下:
可以看到,线程也是同步的,这是因为synchronized修饰静态方法(修饰类),起作用的对象是属于整个类的,就是说只要是该类的对象在调用该类被synchronized修饰的方法时都要保持线程同步。
如果有错误的地方,请欢迎指正!