1. public class TestFive { 
2. private int x; 
3. public void foo() { 
4. int current = x; 
5. x = current + 1; 
6. } 
7. public void go() { 
8. for(int i = 0; i < 5; i++) { 
9. new Thread() { 
10. public void run() { 
11. foo(); 
12. System.out.print(x + ", "); 
13. } }.start(); 
14. } } 
Which two changes, taken together, would guarantee the output: 1, 2, 3, 4, 5, ? (Choose two.) A.  move the line 12 print statement into the foo() method 
B.  change line 7 to public synchronized void go() { 
C.  change the variable declaration on line 2 to private volatile int x; 
D.  wrap the code inside the foo() method with a synchronized( this ) block 
E.  wrap the for loop code inside the go() method with a synchronized block synchronized(this) { // for loop 
    code here } Answer: AD 
想问的是,A为什么对?

解决方案 »

  1.   


    public class TestFive { 
    private int x; 
    public void foo() { 
    int current = x; 
    x = current + 1; 

    public void go() { 
    for(int i = 0; i < 5; i++) { 
    new Thread() { 
    public void run() { 
    foo(); 
    System.out.print(x + ", "); 

    }.start(); 


    public static void main(String[] args){
    new TestFive().go();
    }
    }不需要改变就可以输出1,2,3,4,5,啊!
      

  2.   

    因为在线程中x和控制台都是临界资源
    您必须保证
    int current = x; x = current + 1; 和System.out.print(x + ", "); 操作的原子性,否则,输出的结果将不可预期!