关于java:小哥i是线程安全的吗

6次阅读

共计 4342 个字符,预计需要花费 11 分钟才能阅读完成。

送大家以下 java 学习材料,文末有支付形式


volatile 关键字保障了在多线程环境下, 被润饰的变量在别批改后会马上同步到主存, 这样该线程对这个变量的批改就是对所有其余线程可见的, 其余线程可能马上读到这个批改后值.

Thread 的本地内存

  • 每个 Thread 都领有本人的线程存储空间
  • Thread 何时同步本地存储空间的数据到主存是不确定的

例子

借用 Google JEREMY MANSON 的解释, 上图示意两个线程并发执行, 而且代码程序上为 Thread1->Thread2

1、不必 volatile

如果 ready 字段不应用 volatile, 那么 Thread 1 对 ready 做出的批改对于 Thread2 来说未必是可见的, 是否可见是不确定的. 如果此时 thread1 ready 泄露了 (leak through) 了, 那么 Thread 2 能够看见 ready 为 true, 然而有可能 answer 的扭转并没有泄露, 则 thread2 有可能会输入 0 (answer=42 对 thread2 并不可见)

2、应用 volatile

应用 volatile 当前, 做了如下事件

  • 每次批改 volatile 变量都会同步到主存中
  • 每次读取 volatile 变量的值都强制从主存读取最新的值(强制 JVM 不可优化 volatile 变量, 如 JVM 优化后变量读取会应用 cpu 缓存而不从主存中读取)
  • 线程 A 中写入 volatile 变量之前可见的变量, 在线程 B 中读取该 volatile 变量当前, 线程 B 对其余在 A 中的可见变量也可见. 换句话说, 写 volatile 相似于退出同步块, 而读取 volatile 相似于进入同步块

所以如果应用了 volatile, 那么 Thread2 读取到的值为 read=>true,answer=>42, 当然应用 volatile 的同时也会减少性能开销

留神

volatile 并不能保障非源自性操作的多线程平安问题失去解决,volatile 解决的是多线程间共享变量的 可见性 问题, 而例如多线程的 i ++,++i, 仍然还是会存在多线程问题, 它是无奈解决了. 如下: 应用一个线程 i ++, 另一个 i –, 最终失去的后果不为 0

public class VolatileTest {

    private static volatile int count = 0;
    private static final int times = Integer.MAX_VALUE;

    public static void main(String[] args) {long curTime = System.nanoTime();

        Thread decThread = new DecThread();
        decThread.start();

        // 应用 run()来运行后果为 0, 起因是单线程执行不会有线程平安问题
        // new DecThread().run();

        System.out.println("Start thread:" + Thread.currentThread() + "i++");

        for (int i = 0; i < times; i++) {count++;}

        System.out.println("End thread:" + Thread.currentThread() + "i--");

        // 期待 decThread 完结
        while (decThread.isAlive());

        long duration = System.nanoTime() - curTime;
        System.out.println("Result:" + count);
        System.out.format("Duration: %.2fs\n", duration / 1.0e9);
    }

    private static class DecThread extends Thread {

        @Override
        public void run() {System.out.println("Start thread:" + Thread.currentThread() + "i--");
            for (int i = 0; i < times; i++) {count--;}
            System.out.println("End thread:" + Thread.currentThread() + "i--");
        }
    }
}

最初输入的后果是

Start thread: Thread[main,5,main] i++Start thread: Thread[Thread-0,5,main] i–End thread: Thread[main,5,main] i–End thread: Thread[Thread-0,5,main] i–Result: -460370604Duration: 67.37s

起因是 i ++ 和 ++ i 并非原子操作, 咱们若查看字节码, 会发现

void f1() { i++;}

的字节码如下

void f1();
Code:
0: aload_0
1: dup
2: getfield #2; //Field i:I
5: iconst_1
6: iadd
7: putfield #2; //Field i:I
10: return

可见 i ++ 执行了多部操作, 从变量 i 中读取读取 i 的值 -> 值 +1 -> 将 + 1 后的值写回 i 中, 这样在多线程的时候执行状况就相似如下了

Thread1             Thread2
r1 = i;             r3 = i;
r2 = r1 + 1;        r4 = r3 + 1;
i = r2;             i = r4;

这样会造成的问题就是 r1, r3 读到的值都是 0, 最初两个线程都将 1 写入 i, 最初 i 等于 1, 然而却进行了两次自增操作

可知加了 volatile 和没加 volatile 都无奈解决非原子操作的线程同步问题

线程同步问题的解决

Java 提供了 java.util.concurrent.atomic 包来提供线程平安的根本类型包装类, 例子如下

package com.qunar.atomicinteger;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zhenwei.liu created on 2013 13-9-2 下午 10:18
 * @version $Id$
 */
public class SafeTest {private static AtomicInteger count = new AtomicInteger(0);
    private static final int times = Integer.MAX_VALUE;

    public static void main(String[] args) {long curTime = System.nanoTime();

        Thread decThread = new DecThread();
        decThread.start();

        // 应用 run()来运行后果为 0, 起因是单线程执行不会有线程平安问题
        // new DecThread().run();

        System.out.println("Start thread:" + Thread.currentThread() + "i++");

        for (int i = 0; i < times; i++) {count.incrementAndGet();
        }

        // 期待 decThread 完结
        while (decThread.isAlive());

        long duration = System.nanoTime() - curTime;
        System.out.println("Result:" + count);
        System.out.format("Duration: %.2f\n", duration / 1.0e9);
    }

    private static class DecThread extends Thread {

        @Override
        public void run() {System.out.println("Start thread:" + Thread.currentThread() + "i--");
            for (int i = 0; i < times; i++) {count.decrementAndGet();
            }
            System.out.println("End thread:" + Thread.currentThread() + "i--");
        }
    }
}

输入

Start thread: Thread[main,5,main] i++Start thread: Thread[Thread-0,5,main] i–End thread: Thread[Thread-0,5,main] i–Result: 0Duration: 105.15

论断

  1. volatile 解决了线程间共享变量的可见性问题
  2. 应用 volatile 会减少性能开销
  3. volatile 并不能解决线程同步问题
  4. 解决 i ++ 或者 ++ i 这样的线程同步问题须要应用 synchronized 或者 AtomicXX 系列的包装类, 同时也会减少性能开销
PS:欢送在留言区留下你的观点,一起探讨进步。如果明天的文章让你有新的启发,欢送转发分享给更多人。源于:cnblogs.com/zemliu/p/3298685.html

正文完
 0