public class TestSeven extends Thread {
private static int x;
public synchronized void doThings() {
int current = x;
current++;
x = current;
}
public void run() {
doThings();
}
}
Which statement is true?
A. Compilation fails.
B. An exception is thrown at runtime.
C. Synchronizing the run() method would make the class thread-safe.
D. The data in variable "x" are protected from concurrent access problems.
E. Declaring the doThings() method as static would make the class thread-safe.
F. Wrapping the statements within doThings() in a synchronized(new Object()) { } block would make the
class
thread-safe.
Answer: E
怎么看怎么是D,是否答案错了
------------------------------------
因为 doThings是非静态函数,synchronized锁定的是当前对象。如果存在多个TestSeven对象,那么不同对象的方法分别锁定不同的对象,就会存在同步问题了。同步的核心是要锁定同一个对象。因此答案为E而不是D.
ps:对于代码里,要想达到thread-safe,要么把x改成非静态的,要么把doThings()改成静态的.
------------------------------------------
因为x是static的,所以是被所有TestSeven对象共享的,所以多个线程对象TestSeven执行doThings方法时,虽然这个方法是 synchronized的,但是锁对象是this,所以说一个线程对象的doThings方法中更改了x,在另一个线程对象却可以得到他本身的锁标记而执行doThings方法,但其中x被更改,就存在了安全问题。
把方法也换成static后可保证线程安全
普通同步方法锁定的是与 this 相关联的监视器;而静态同步方法则是与包含该方法的类所对应的 Class 对象相关联的监视器;
所以说每个静态方法的锁对象都是相同的,因此不会出现上面那种不安全的因素
不知道自己表达清除了吗...
----------------------------------------------
我只部分同意你,看这段代码,x是在每个独立的线程中修改的,即使同时多个TestSevent运行那又有什么影响?x是先赋值给本地变量current,计算发生在current,然后再赋值给x,所以我认为不存在线程安全问题,赋值是个原子操作。
----------------------------------------
x是一个static的啊,试想一下,两个TestSeventd对象t1,t2,由于x是static的,所以t1,t2共享一个x
t1.start(),t2.start()
t1线程执行
Java code
public synchronized void doThings() { int current = x; //1 假设此时x=1 current++; //2 x = current; //3 }
应该在此次调用doThings后,x=2
但是在线程还没有执行1的时候,该线程的时间片段用完,cup交给另一个线程t2
t2也执行doThings()一次,把x修改成2,然后继续回到t1线程中,t1的doThings继续执行,执行完后,x=3,而不是2,出现了问题
由于是两个TestSeventd,所以两个线程之间没有互斥作用(即那个锁没起作用),而x又是static的,所以这样做不安全