Java多线程 synchronized修饰的用法的浅谈

看到网上不少资料都讲解synchronized的用法详解,确实有不少的知识点,但初学者可能看的比较头晕,这里浅谈下很重要的synchronized修饰普通方法和修饰静态方法,也是在实际开发中用的比较多的。java

这里先说synchronized修饰普通方法,修饰代码块和修饰静态方法的最大特色:安全

修饰普通方法,修饰代码块:只针对调用它的对象起做用。this

修饰静态方法:针对该类的全部对象都起做用。线程

直接上代码:code

​
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();
        });
    }
}

​

输出结果:对象

能够看出,两个线程很好的保持了同步,达到了线程安全的效果,blog

出现这个的缘由是:在test1方法中,咱们使用同一个对象调用它,因此每一个线程都要依次得到该对象的锁才能执行,这里注意的是,起做用的是该对象(同一个),下面调用test2方法结果也一致,由于执行代码都在synchronized里被修饰了。开发

可是若是咱们新增长一个对象,分别调用本身的test1方法,以下:同步

SyncTest syncTest1 = new SyncTest();
        SyncTest syncTest2 = new SyncTest();
        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.execute(() ->{
            syncTest1.test2();
        });
        executorService.execute(() ->{
            syncTest2.test2();
        });

结果:
class

能够看到,结果是线程不一样步的,这是由于用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修饰的方法时都要保持线程同步。

若是有错误的地方,请欢迎指正!

相关文章
相关标签/搜索