Java多线程笔记二(synchronized的使用以及实现原理)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/login_sonata/article/details/78010520

同步关键字synchronized

java关键字synchronized用来标记方法或者代码块是同步的。它是Java中解决并发问题的一种最常用的方法,作用主要有:(1)确保线程互斥的访问同步代码(2)保证共享变量的修改能够及时可见。
synchronized总共有四种用法:
(1)修饰普通方法
(2)修饰静态方法
(3)修饰普通方法中的代码块
(4)修饰静态方法中的代码块

修饰普通方法

public class SynchronizedTest {
    //方法1,执行3秒
    public synchronized void method1() {
        System.out.println("method1 start");
        try {
            System.out.println("method1 execute");
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("method1 end");
    }
    //方法2,执行1秒
    public synchronized void method2() {
        System.out.println("method2 start");
        try {
            System.out.println("method2 execute");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("method2 end");
    }
    public static void main(String[] args) {
        final SynchronizedTest test = new SynchronizedTest();
        //线程1
        new Thread(new Runnable() {
            @Override
            public void run() {
                test.method1();
            }
        }).start();
        //线程2
        new Thread(new Runnable() {
            @Override
            public void run() {
                test.method2();
            }
        }).start();
    }
}

输出:

method1 start
method1 execute
method1 end
method2 start
method2 execute
method2 end

synchronized 关键字告诉Java该方法是同步的。同步,是同步在拥有该方法的对象上。对于一个实例来说,只有一个线程能够在这个方法同步块中运行。如果有多个实例存在,每一个实例对应一个线程。
在本例中,线程2需要等待线程1的method1执行完成才能开始执行method2方法。因为对于test实例来说,同一时间只有一个线程能够运行它的同步方法。

如果把本例中的synchronized 关键字去掉,输出为:

method1 start
method1 execute
method2 start
method2 execute
method2 end
method1 end

因为线程1和线程2同时进入执行状态,方法2执行速度比方法1快,所以方法2先执行完成,这个过程中线程1和线程2是同时执行的。

修饰静态方法

public class SynchronizedTest {
    //方法1,执行3秒
    public static synchronized void method1() {
        System.out.println("method1 start");
        try {
            System.out.println("method1 execute");
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("method1 end");
    }
    //方法2,执行1秒
    public static synchronized void method2() {
        System.out.println("method2 start");
        try {
            System.out.println("method2 execute");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("method2 end");
    }
    public static void main(String[] args) {
        final SynchronizedTest test1 = new SynchronizedTest();
        final SynchronizedTest test2 = new SynchronizedTest();
        //线程1
        new Thread(new Runnable() {
            @Override
            public void run() {
                test1.method1();
            }
        }).start();
        //线程2
        new Thread(new Runnable() {
            @Override
            public void run() {
                test2.method2();
            }
        }).start();
    }
}

输出:

method1 start
method1 execute
method1 end
method2 start
method2 execute
method2 end

对静态方法的同步本质上是对类的同步(静态方法本质上是属于类的方法,而不是对象上的方法),所以即使test1和test2属于不同的对象,但是它们都属于SynchronizedTest类的实例,所以也只能挨个顺序执行线程,不能并发执行。

修饰普通方法中的代码块

有时你不需要同步整个方法,而是同步方法中的一部分。

public class SynchronizedTest {
    //方法1,执行3秒
    public void method1() {
        System.out.println("method1 start");
        try {
            synchronized(this){
                System.out.println("method1 execute");
                Thread.sleep(3000);
            }
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("method1 end");
    }
    //方法2,执行1秒
    public void method2() {
        System.out.println("method2 start");
        try {
            synchronized(this){
                System.out.println("method2 execute");
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("method2 end");
    }
    public static void main(String[] args) {
        final SynchronizedTest test = new SynchronizedTest();
        //线程1
        new Thread(new Runnable() {
            @Override
            public void run() {
                test.method1();
            }
        }).start();
        //线程2
        new Thread(new Runnable() {
            @Override
            public void run() {
                test.method2();
            }
        }).start();
    }
}

输出:

method1 start
method1 execute
method2 start
method1 end
method2 execute
method2 end

虽然线程1和线程2都进入了对应的方法开始执行,但是线程2在进入同步块之前,需要等待线程1中同步块执行完成。

在同步构造器中用括号括起来的对象叫做监视器对象。在上例中,使用了this,即为调用该方法的实例本身。上述代码使用监视器对象同步,并使用调用方法本身的实例作为监视器对象。同一时间只有一个线程能够运行同一个监视器对象的同步块代码。

扫描二维码关注公众号,回复: 3312202 查看本文章

修饰静态方法中的代码块

这和“修饰普通方法中的代码块”非常类似,只需要把监视器对象改为类对象即可。以上边的程序为例,把synchronized(this)改为synchronized(SynchronizedTest.class)即可。

synchronized原理

同步块程序的反编译

我们先通过反编译下面的代码来看看Synchronized是如何实现对同步块进行同步的:

package com.paddx.test.concurrent;
public class SynchronizedDemo {
    public void method() {
        synchronized (this) {
            System.out.println("Method 1 start");
        }
    }
}

反编译结果:
这里写图片描述
红色框中的这两条指令(monitorentermonitorexit)的作用是什么?先看monitorenter

每个对象有一个监视器锁(monitor)。当monitor被占用时就会处于锁定状态,线程执行monitorenter指令时尝试获取monitor的所有权,过程如下:
(1)如果monitor的进入数为0,则该线程进入monitor,然后将进入数设置为1,该线程即为monitor的所有者。
(2)如果线程已经占有该monitor,只是重新进入,则进入monitor的进入数加1。
(3)如果其他线程已经占用了monitor,则该线程进入阻塞状态,直到monitor的进入数为0,再重新尝试获取monitor的所有权。

再看monitorexit: 

执行monitorexit的线程必须是objectref所对应的monitor的所有者。
指令执行时,monitor的进入数减1,如果减1后进入数为0,那线程退出monitor,不再是这个monitor的所有者。其他被这个monitor阻塞的线程可以尝试去获取这个monitor 的所有权。

通过上边两段描述,我们可以看出在同步代码块中synchronized的实现原理,是通过一个monitor的对象来完成,其实wait/notify等方法也依赖于monitor对象,这就是为什么只有在同步的块或者方法中才能调用wait/notify等方法,否则会抛出java.lang.IllegalMonitorStateException异常的原因。

同步方法的反编译:

这里写图片描述
从反编译的结果来看,方法的同步并没有通过指令monitorentermonitorexit来完成(理论上其实也可以通过这两条指令来实现),不过其常量池中多了ACC_SYNCHRONIZED标示符。JVM就是根据该标示符来实现方法的同步的,具体的:
当方法调用时,调用指令将会检查方法的 ACC_SYNCHRONIZED 访问标志是否被设置,如果设置了,执行线程将先获取monitor,获取成功之后才能执行方法体,方法执行完后再释放monitor。在方法执行期间,其他任何线程都无法再获得同一个monitor对象。 其实本质上没有区别,只是方法的同步是一种隐式的方式来实现,无需通过字节码来完成。

回顾

有了对Synchronized原理的认识,再来看上面的程序就可以迎刃而解了。
(1)“修饰普通方法”一节中的例子:
虽然method1和method2是不同的方法,但是这两个方法都进行了同步,并且是通过同一个对象去调用的,所以调用之前都需要先去竞争同一个对象上的锁(monitor),也就只能互斥的获取到锁,因此,method1和method2只能顺序的执行。

(2)“修饰静态方法”一节中的例子:
虽然test1和test2属于不同对象,但是test1和test2属于同一个类的不同实例,由于method1和method2都属于静态同步方法,所以调用的时候需要获取同一个类上的monitor(每个类只对应一个class对象),所以也只能顺序的执行。

(3)“修饰普通方法中的代码块”一节的例子:
对于代码块的同步实质上需要获取synchronized关键字后面括号中对象的monitor,由于这段代码中括号的内容都是this,而method1和method2又是通过同一的对象去调用的,所以进入同步块之前需要去竞争同一个对象上的锁,因此只能顺序执行同步块。


原文来自:并发编程网-Java同步块
liuxiaopeng-Java并发编程:Synchronized及其实现原理

猜你喜欢

转载自blog.csdn.net/login_sonata/article/details/78010520
今日推荐