- Volatile关键字的主要作用是使变量在多个线程间可见。
- 在java中,每一个线程都会有一块内存区,其中存放着所有线程共享的主内存中变量值的拷贝,当线程执行时,他在自己的工作内存中操作这些变量,为了存取一个共享变量,一个线程通常先获取锁定并清除他的内存工作区,把这些变量从所有的共享内存区中装入到他自己所在的工作内存区中,当线程结束时保证该工作内存区中变量的值回到共享内存中。
- Volatile的作用就是强制线程到主内存里去读取变量,而不是去线程内存区里读取,从而实现了多个线程间变量的可见性,也就是满足线程安全的可见性。
- public class RunThread extends Thread{
- 使用volatile关键字
- private volatile boolean isRunning = true;
- private void setRunning(boolean isRunning){
- this.isRunning = isRunning;
- }
- public void run(){
- System.out.println("进入run方法..");
- int i = 0;
- while(isRunning == true){
- //..
- }
- System.out.println("线程停止");
- }
- public static void main(String[] args) throws InterruptedException {
- RunThread rt = new RunThread();
- rt.start();
- Thread.sleep(1000);
- rt.setRunning(false);
- System.out.println("isRunning的值已经被设置了false");
- }
- }
- 输出结果:
- 进入run方法..
- isRunning的值已经被设置了false
- 线程停止
- public class RunThread extends Thread{
- private boolean isRunning = true;
- private void setRunning(boolean isRunning){
- this.isRunning = isRunning;
- }
- public void run(){
- System.out.println("进入run方法..");
- int i = 0;
- while(isRunning == true){
- //..
- }
- System.out.println("线程停止");
- }
- public static void main(String[] args) throws InterruptedException {
- RunThread rt = new RunThread();
- rt.start();
- Thread.sleep(1000);
- rt.setRunning(false);
- System.out.println("isRunning的值已经被设置了false");
- }
- }
- 输出结果:未使用volatile关键字,isRunning改变,线程未发现改变。
- 进入run方法..
- isRunning的值已经被设置了false
- Volatile关键字拥有多个线程的可见性,却不具备同步性(原子性)可以算是一个轻量级的synchronized,性能比synchronized强的多,不会造成阻塞,。Volatile只针对多线程可见性,并不能替换sychronized同步的功能。
- public class AtomicUse {
- 可见的但不同步
- private static AtomicInteger count = new AtomicInteger(0);
- //多个addAndGet在一个方法内是非原子性的,需要加synchronized进行修饰,保证4个addAndGet整体原子性
- /**synchronized*/同步
- 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) {
- 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();
- }
- }
- }
- 输出结果:
- 10
- 20
- 30
- 40
- 50
- 60
- …………………….
6.volatile关键字。

最新推荐文章于 2025-04-07 21:38:44 发布
