静态变量的线程安全 [英] Thread safety for static variables

查看:76
本文介绍了静态变量的线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class ABC implements Runnable {
    private static int a;
    private static int b;
    public void run() {
    }
}

我有一个上面的Java类.我有此类的多个线程.在run()方法中,变量a& b分别递增几次.每次增加时,我都会将这些变量放入哈希表中.

I have a Java class as above. I have multiple threads of this class. In the run() method, the variables a & b are incremented each for several times. On each increment, I am putting these variables in a Hashtable.

因此,每个线程将增加两个变量并将它们放入Hashtable中.如何使这些操作线程安全?

Hence, each thread will increment both variables and putting them in Hashtable. How can I make these operations thread safe?

推荐答案

我会使用

I would use AtomicInteger, which is designed to be thread-safe and is dead easy to use and imparts the absolute minimal of synchronization overhead to the application:

class ABC implements Runnable {
    private static AtomicInteger a;
    private static AtomicInteger b;
    public void run() {
        // effectively a++, but no need for explicit synchronization!
        a.incrementAndGet(); 
    }
}

// In some other thread:

int i = ABC.a.intValue(); // thread-safe without explicit synchronization

这篇关于静态变量的线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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