Given:
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。

解决方案 »

  1.   

    不对的。如果没有主函数,抛出的是错误,而不是B说的Exception:
    Error: Main method not found in class TestSeven, please define the main method as:
       public static void main(String[] args)
      

  2.   

    我试回一下 D EA.程序无编译错误
    B.运行期不会有错
    C.同步run只能使run方法线程安全,无法使类线程安全
    D.x因为是私有,而且只暴露在同步方法中,因此安全
    E.这个同意,操作此类数据的入口全在doThings方法了
    F.尚不能使doThings方法安全,每次都是一把新锁,遑论class thread-safe了
      

  3.   

    我觉得答案是E
    A。错误,能编译
    B。运行时异常,也不对
    C.同步对象的方法不能保证静态属性的线程安全,错
    D.没怎么看懂,x不是安全的,错误
    E.doThings这个如果定义为静态的,能保证static的属性是线程安全的,正确
    F.明显不对,在synchronized中使用new
      

  4.   

    C不安全是因为这个方法是同步的当前对象,如果多个对象还是能同时调用这个方法,而x是静态的,多个对象共享的,所以是不安全的。只有定义为同步的静态方法,锁定对象是当前类,才是安全的。
    [Quote=引用 3 楼 dracularking 的回复:]
    D.x因为是私有,而且只暴露在同步方法中,因此安全