How to synchronize a static variable among threads running different instances of a class in Java?(java - 如何在Java中运行类的不同实例的线程之间同步静态变量?)
问题描述
我知道在方法之前使用 synchronize
关键字会同步到该对象.也就是说,运行同一对象实例的 2 个线程将被同步.
I know that using the synchronize
keyword before a method brings synchronization to that object. That is, 2 threads running the same instance of the object will be synchronized.
但是,由于同步是在对象级别进行的,因此运行该对象的不同实例的 2 个线程将不会同步.如果我们在方法调用的 Java 类中有一个静态变量,我们希望它在类的实例之间同步.这两个实例在 2 个不同的线程中运行.
However, since the synchronization is at the object level, 2 threads running different instances of the object will not be synchronized. If we have a static variable in a Java class that is called by the method, we would like it to be synchronized across instances of the class. The two instances are running in 2 different threads.
我们可以通过以下方式实现同步吗?
Can we achieve synchronization in the following way?
public class Test
{
private static int count = 0;
private static final Object lock= new Object();
public synchronized void foo()
{
synchronized(lock)
{
count++;
}
}
}
是不是因为我们已经定义了一个静态对象lock
,并且我们为那个锁使用关键字synchronized
,所以静态变量count
现在在类 Test
的实例之间同步?
Is it true that since we have defined an object lock
that is static and we are using the keyword synchronized
for that lock, the static variable count
is now synchronized across instances of class Test
?
推荐答案
有几种方法可以同步访问静态变量.
There are several ways to synchronize access to a static variable.
使用同步的静态方法.这会在类对象上同步.
Use a synchronized static method. This synchronizes on the class object.
public class Test {
private static int count = 0;
public static synchronized void incrementCount() {
count++;
}
}
在类对象上显式同步.
Explicitly synchronize on the class object.
public class Test {
private static int count = 0;
public void incrementCount() {
synchronized (Test.class) {
count++;
}
}
}
在其他静态对象上同步.
Synchronize on some other static object.
public class Test {
private static int count = 0;
private static final Object countLock = new Object();
public void incrementCount() {
synchronized (countLock) {
count++;
}
}
}
方法 3 在许多情况下是最好的,因为锁定对象不会暴露在你的类之外.
Method 3 is the best in many cases because the lock object is not exposed outside of your class.
这篇关于java - 如何在Java中运行类的不同实例的线程之间同步静态变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:java - 如何在Java中运行类的不同实例的线程之间同步静态变量?
基础教程推荐
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01