原始数据类型是否在Java中是线程安全的 [英] Are primitive datatypes thread-safe in Java

查看:274
本文介绍了原始数据类型是否在Java中是线程安全的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

原始数据类型是 int & Java中的线程安全?我已执行以下代码,有时无法看到预期的结果500.

Are the primitive data types like int & short thread-safe in Java? I have executed the following code and couldn't see expected result 500 some times.

public class SampleThree extends Thread
{
    static long wakeUpTime = System.currentTimeMillis() + (1000*20);
    static int inT;
    public static void main(String args[])
    {
        System.out.println("initial:" + inT);
        for(int i=0; i<500; i++)
            new SampleThree().start();
        try {
            Thread.sleep(wakeUpTime - System.currentTimeMillis() + (1000*30));
            System.out.println("o/p:" + inT);
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }

    public void run()
    {
        try {
            long s = wakeUpTime - System.currentTimeMillis();
            System.out.println("will sleep ms: " + s);
            Thread.sleep(s);
            inT++; // System.out.println(inT);
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }
}

此处同时500个线程将更新int变量 inT 。等待并发更新完成后的主线程打印 inT 值。

Here concurrently 500 thread will update the int variable inT. Main thread after waiting for concurrent update to be completed, prints inT value.

查找类似示例其他

推荐答案

他们有三种不安全的方式:

There are three ways in which they're not safe:


  • long double 甚至不能保证以原子方式更新(你可以看到来自不同线程的写入的一半)

  • 内存模型不保证你会看到另一个线程中一个线程的最新更新,没有额外的内存障碍

  • 增量行为一个变量不是原子的

  • long and double aren't even guaranteed to be updated atomically (you could see half of a write from a different thread)
  • The memory model doesn't guarantee that you'll see the latest updates from one thread in another thread, without extra memory barriers of some kind
  • The act of incrementing a variable isn't atomic anyway

使用 AtomicInteger 等用于线程安全操作。

Use AtomicInteger etc for thread-safe operations.

这篇关于原始数据类型是否在Java中是线程安全的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆