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,是否答案错了
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,是否答案错了
解决方案 »
- 每日一题5
- 编译java文件出来了两注意,tell me why?
- 第一次在Java块发贴:Java与C++在基本语法层面的不同。 希望指点。
- Java到".txt"文件回车换行写入的问题
- 在JSP中,有什么免费的报表API推荐
- java里面有没有类似js中的split函数,返回一个数组
- 获取系统时间 public Date getCurrentDate(String formatter)//formatter为格式如yyyy/mm/dd,如何写?
- 十万火急在线等!
- 谁知道哪里有<<Java thinking>>第二版下载?
- 十萬為急,明天要完成,郵件發送失敗問題,請高手指點????,在線等待。
- SCJP 6.0認證教戰手冊考題.228---锁的问题
- 求教一个java和数据库交互的小程序
因为x是static的,所以是被所有TestSeven对象共享的,所以多个线程对象TestSeven执行doThings方法时,虽然这个方法是synchronized的,但是锁对象是this,所以说一个线程对象的doThings方法中更改了x,在另一个线程对象却可以得到他本身的锁标记而执行doThings方法,但其中x被更改,就存在了安全问题。
把方法也换成static后可保证线程安全
普通同步方法锁定的是与 this 相关联的监视器;而静态同步方法则是与包含该方法的类所对应的 Class 对象相关联的监视器;
所以说每个静态方法的锁对象都是相同的,因此不会出现上面那种不安全的因素
不知道自己表达清除了吗...
t1.start(),t2.start()
t1线程执行
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的,所以这样做不安全