首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

SCJP考题一道:线程安全解决方案

2012-01-19 
SCJP考题一道:线程安全Given:Java code1. public class TestSeven extends Thread {2. private static int

SCJP考题一道:线程安全
Given:

Java code
1. public class TestSeven extends Thread {2. private static int x;3. public synchronized void doThings() {4. int current = x;5. current++;6. x = current;7. }8. public void run() {9. doThings();10. }11.}

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.


该选哪个,为什么?

thx。

[解决办法]
这个函数没有主函数啊 ....B应该选吧
[解决办法]
我试回一下 D E

A.程序无编译错误
B.运行期不会有错
C.同步run只能使run方法线程安全,无法使类线程安全
D.x因为是私有,而且只暴露在同步方法中,因此安全
E.这个同意,操作此类数据的入口全在doThings方法了
F.尚不能使doThings方法安全,每次都是一把新锁,遑论class thread-safe了
[解决办法]
我觉得答案是E
A。错误,能编译
B。运行时异常,也不对
C.同步对象的方法不能保证静态属性的线程安全,错
D.没怎么看懂,x不是安全的,错误
E.doThings这个如果定义为静态的,能保证static的属性是线程安全的,正确
F.明显不对,在synchronized中使用new
[解决办法]
E文残念。。。。
[解决办法]
选e吧。

热点排行