一、valitile的概念
volatile关键字的主要作用是使变量在多个线程间可见
二、共享变量在多个线程间不可见
public class RunThread extends Thread{
private boolean isRunning = true;
private void setRunning(boolean isRunning){
this.isRunning = isRunning;
}
@Override
public void run(){
System.out.println("进入run方法..");
while(isRunning == true){
}
System.out.println("线程停止");
}
public static void main(String[] args) throws InterruptedException {
RunThread rt = new RunThread();
rt.start();
Thread.sleep(3000);
rt.setRunning(false);
System.out.println("isRunning的值已经被设置了false");
Thread.sleep(1000);
System.out.println(rt.isRunning);
}
}
执行上述代码,其输出结果为:
进入run方法..
isRunning的值已经被设置了false
false
可以看到主线程已经将isRunning变量的值设置为true,但是线程rt并没有感知到isRunning变量的值被修改了,依旧在做while循环操作。
三、volatile关键字使用解析
在Java中,每一个线程都会有一块自己的工作内存区,其中存放着所有线程共享的主内存中的变量值的拷贝。当线程执行时,它会在自己的工作内存区中操作这些变量。当线程执行完以后才会把工作内存中变量的值写回到主内存中。
针对前面的问题,我们可以在共享变量isRunning的声明处添加volatile关键字:
public class RunThread extends Thread{
private volatile boolean isRunning = true;
private void setRunning(boolean isRunning){
this.isRunning = isRunning;
}
@Override
public void run(){
System.out.println("进入run方法..");
while(isRunning == true){
}
System.out.println("线程停止");
}
public static void main(String[] args) throws InterruptedException {
RunThread rt = new RunThread();
rt.start();
Thread.sleep(3000);
rt.setRunning(false);
System.out.println("isRunning的值已经被设置了false");
Thread.sleep(1000);
System.out.println(rt.isRunning);
}
}
执行上述代码,其输出结果为:
进入run方法..
isRunning的值已经被设置了false
线程停止
false
可以看到主线程将isRunning变量的值设置为true后,线程rt感知到了isRunning变量的值发生变化,就跳出while循环停止。下面这个是添加了volatile关键字以后线程rt在内存中使用isRunning变量值的流程图:
volatile的作用就是强制线程到主内存里去读取变量,而不去线程工作内存里去读取,从而实现了多个线程间的变量可见。
四、volatile关键字的非原子性
volatile关键字虽然拥有多个线程之间的可见性,但是却不具备同步性(也就是原子性),可以算上是一个轻量级的synchronized,性能要比synchronized强很多,不会造成阻塞(在很多开源的架构里,比如netty的底层代码就大量使用volatile,可见netty性能一定是非常不错的)。
注意:一般volatile用于只针对多个线程可见的变量操作,并不能代替synchronized的同步功能。
public class VolatileNoAtomic extends Thread{
private static volatile int count;
private static void addCount(){
for (int i = 0; i < 1000; i++) {
count++ ;
}
System.out.println(count);
}
@Override
public void run(){
addCount();
}
public static void main(String[] args) {
VolatileNoAtomic[] arr = new VolatileNoAtomic[100];
for (int i = 0; i < 10; i++) {
arr[i] = new VolatileNoAtomic();
}
for (int i = 0; i < 10; i++) {
arr[i].start();
}
}
}
执行上述代码,其输出结果为:
1823
2823
1823
3823
5823
6823
4823
7823
8823
9823
10个线程对同一个变量count进行操作,但是最终变量count的值并不是10000。
volatile关键字只具有可见性,没有原子性。要实现原子性建议使用atomic类的系列对象,支持原子性操作
import java.util.concurrent.atomic.AtomicInteger;
public class VolatileNoAtomic extends Thread{
private static AtomicInteger count = new AtomicInteger(0);
private static void addCount(){
for (int i = 0; i < 1000; i++) {
count.incrementAndGet();
}
System.out.println(count);
}
@Override
public void run(){
addCount();
}
public static void main(String[] args) throws Exception{
VolatileNoAtomic[] arr = new VolatileNoAtomic[100];
for (int i = 0; i < 10; i++) {
arr[i] = new VolatileNoAtomic();
}
for (int i = 0; i < 10; i++) {
arr[i].start();
}
}
}
执行上述代码,其输出结果为:
5000
6000
5917
7053
8000
9000
6000
5000
5000
10000
注意:atomic类只保证本身方法原子性,并不保证多次操作的原子性
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicUse {
private static AtomicInteger count = new AtomicInteger(0);
//多个addAndGet在一个方法内是非原子性的,需要加synchronized进行修饰,保证4个addAndGet整体原子性
public synchronized int multiAdd() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
count.addAndGet(1);
count.addAndGet(2);
count.addAndGet(3);
count.addAndGet(4); //+10
return count.get();
}
public static void main(String[] args) throws Exception{
final AtomicUse au = new AtomicUse();
List<Thread> ts = new ArrayList<Thread>();
for (int i = 0; i < 100; i++) {
ts.add(new Thread(new Runnable() {
@Override
public void run() {
System.out.println(au.multiAdd());
}
}));
}
for (Thread t : ts) {
t.start();
}
}
}