您的位置:首页 > 其它

volatile与synchronized的区别

2021-03-02 21:49 357 查看

1. volatile修饰的变量具有可见性


从图中可以看出:

①每个线程都有一个自己的本地内存空间–线程栈空间???线程执行时,先把变量从主内存读取到线程自己的本地内存空间,然后再对该变量进行操作

②对该变量操作完后,在某个时间再把变量刷新回主内存

public class RunThread extends Thread {

 private boolean isRunning = true;

 public boolean isRunning() {
 return isRunning;
 }

 public void setRunning(boolean isRunning) {
 this.isRunning = isRunning;
 }

 @Override
 public void run() {
 System.out.println("进入到run方法中了");
 while (isRunning == true) {
 }
 System.out.println("线程执行完成了");
 }
}

public class Run {
 public static void main(String[] args) {
 try {
 RunThread thread = new RunThread();
 thread.start();
 Thread.sleep(1000);
 thread.setRunning(false);
 } catch (InterruptedException e) {
 e.printStackTrace();
 }
 }
}

Run.java 第28行,main线程 将启动的线程RunThread中的共享变量设置为false,从而想让RunThread.java 第14行中的while循环结束。

如果,我们使用JVM -server参数执行该程序时,RunThread线程并不会终止!从而出现了死循环!!

原因分析:

现在有两个线程,一个是main线程,另一个是RunThread。它们都试图修改 第三行的 isRunning变量。按照JVM内存模型,main线程将isRunning读取到本地线程内存空间,修改后,再刷新回主内存。

而在JVM 设置成 -server模式运行程序时,线程会一直在私有堆栈中读取isRunning变量。因此,RunThread线程无法读到main线程改变的isRunning变量

从而出现了死循环,导致RunThread无法终止。这种情形,在《Effective JAVA》中,将之称为“活性失败”

解决方法,在第三行代码处用 volatile 关键字修饰即可。这里,它强制线程从主内存中取 volatile修饰的变量。

2. volatile禁止指令重排

所谓原子性,就是某系列的操作步骤要么全部执行,要么都不执行。

比如,变量的自增操作 i++,分三个步骤:

①从内存中读取出变量 i 的值

②将 i 的值加1

③将 加1 后的值写回内存

这说明 i++ 并不是一个原子操作。因为,它分成了三步,有可能当某个线程执行到了第②时被中断了,那么就意味着只执行了其中的两个步骤,没有全部执行。

关于volatile的非原子性,看个示例:

public class MyThread extends Thread {
 public volatile static int count;

 private static void addCount() {
 for (int i = 0; i < 100; i++) {
 count++;
 }
 System.out.println("count=" + count);
 }

 @Override
 public void run() {
 addCount();
 }
}

public class Run {
 public static void main(String[] args) {
 MyThread[] mythreadArray = new MyThread[100];
 for (int i = 0; i < 100; i++) {
 mythreadArray[i] = new MyThread();
 }

 for (int i = 0; i < 100; i++) {
 mythreadArray[i].start();
 }
 }
}

MyThread类第2行,count变量使用volatile修饰

Run.java 第20行 for循环中创建了100个线程,第25行将这100个线程启动去执行 addCount(),每个线程执行100次加1

期望的正确的结果应该是 100*100=10000,但是,实际上count并没有达到10000

原因是:volatile修饰的变量并不保证对它的操作(自增)具有原子性。(对于自增操作,可以使用JAVA的原子类AutoicInteger类保证原子自增)

比如,假设 i 自增到 5,线程A从主内存中读取i,值为5,将它存储到自己的线程空间中,执行加1操作,值为6。此时,CPU切换到线程B执行,从主从内存中读取变量i的值。由于线程A还没有来得及将加1后的结果写回到主内存,线程B就已经从主内存中读取了i,因此,线程B读到的变量 i 值还是5

相当于线程B读取的是已经过时的数据了,从而导致线程不安全性。这种情形在《Effective JAVA》中称之为“安全性失败”

综上,仅靠volatile不能保证线程的安全性。(原子性)

3.  synchronized

synchronized可作用于一段代码或方法,既可以保证可见性,又能够保证原子性。

可见性体现在:通过synchronized或者Lock能保证同一时刻只有一个线程获取锁然后执行同步代码,并且在释放锁之前会将对变量的修改刷新到主存中。

原子性表现在:要么不执行,要么执行到底。

如果对上面的执行结果还有疑问,也先不用急,我们先来了解Synchronized的原理,再回头上面的问题就一目了然了。我们先通过反编译下面的代码来看看Synchronized是如何实现对代码块进行同步的:

package com.paddx.test.concurrent;

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

反编译结果:

关于这两条指令的作用,我们直接参考JVM规范中描述:

monitorenter :

Each object is associated with a monitor. A monitor is locked if and only if it has an owner. The thread that executes monitorenter attempts to gain ownership of the monitor associated with objectref, as follows:
• If the entry count of the monitor associated with objectref is zero, the thread enters the monitor and sets its entry count to one. The thread is then the owner of the monitor.
• If the thread already owns the monitor associated with objectref, it reenters the monitor, incrementing its entry count.
• If another thread already owns the monitor associated with objectref, the thread blocks until the monitor’s entry count is zero, then tries again to gain ownership.

这段话的大概意思为:

每个对象有一个监视器锁(monitor)。当monitor被占用时就会处于锁定状态,线程执行monitorenter指令时尝试获取monitor的所有权,过程如下:

1、如果monitor的进入数为0,则该线程进入monitor,然后将进入数设置为1,该线程即为monitor的所有者。

2、如果线程已经占有该monitor,只是重新进入,则进入monitor的进入数加1.

3.如果其他线程已经占用了monitor,则该线程进入阻塞状态,直到monitor的进入数为0,再重新尝试获取monitor的所有权。

monitorexit:

The thread that executes monitorexit must be the owner of the monitor associated with the instance referenced by objectref.
The thread decrements the entry count of the monitor associated with objectref. If as a result the value of the entry count is zero, the thread exits the monitor and is no longer its owner. Other threads that are blocking to enter the monitor are allowed to attempt to do so.

这段话的大概意思为:

执行monitorexit的线程必须是objectref所对应的monitor的所有者。

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

通过这两段描述,我们应该能很清楚的看出Synchronized的实现原理,Synchronized的语义底层是通过一个monitor的对象来完成,其实wait/notify等方法也依赖于monitor对象,这就是为什么只有在同步的块或者方法中才能调用wait/notify等方法,否则会抛出java.lang.IllegalMonitorStateException的异常的原因。

Synchronized是Java并发编程中最常用的用于保证线程安全的方式,其使用相对也比较简单。但是如果能够深入了解其原理,对监视器锁等底层知识有所了解,一方面可以帮助我们正确的使用Synchronized关键字,另一方面也能够帮助我们更好的理解并发编程机制,有助我们在不同的情况下选择更优的并发策略来完成任务。对平时遇到的各种并发问题,也能够从容的应对。

总结

1.volatile仅能使用在变量级别;  synchronized则可以使用在变量、方法、和类级别的

2.volatile仅能实现变量的修改可见性,并不能保证原子性;synchronized则可以保证变量的修改可见性 8000 和原子性

3.volatile不会造成线程的阻塞; synchronized可能会造成线程的阻塞。

4.volatile标记的变量不会被编译器优化;synchronized标记的变量可以被编译器优化


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: