本文介绍了静态变量的线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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?
推荐答案
我会使用 AtomicInteger ,它被设计为线程安全的,非常容易使用,并为应用程序带来了最小的同步开销:
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
这篇关于静态变量的线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!