给定:
public class TestSeven extends Thread {
private static int x;
public synchronized void doThings() {
int current = x;
current++;
x = current;
}
public void run() {
doThings();
}
}
哪个说法是正确的?
一个。编译失败。
B.运行时抛出异常。
C.同步 run() 方法将使类线程安全。
D.变量“x”中的数据不受并发访问问题的影响。
E.将 doThings() 方法声明为静态方法将使该类成为线程安全的。
F.将 doThings() 中的语句包装在 synchronized(new Object()) { } block 中将使该类线程安全。
将 doThings() 标记为同步以使该类线程安全还不够吗?我看到正确答案是 D 但此问题的标准答案是 E,但我不明白为什么?
最佳答案
E. Declaring the doThings() method as static would make the class thread-safe.
这是一个棘手的答案。该方法已经同步,但在实例上,而状态在静态字段中,即在类上。使其成为 static synchronized
确实是正确的答案,因为这样它就会在类上同步,而不是在(无意义的)实例上同步。
D. The data in variable "x" are protected from concurrent access problems.
private static int x;
这是一个静态变量。它由该类的所有实例共享,因此对单个实例进行同步没有帮助,就像 F 没有帮助一样,它对一个完整的一次性虚拟对象进行同步。
关于java - 使类线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12292486/