public class PingPong implements Runnable{
       synchronized void hit(long n){
            for(int i=1; i<3; i++) 
                System.out.print(n + "-" + i + " ");
       } 
       public static void main(String[] args){ 
           new Thread(new PingPong()).start(); 
           new Thread(new PingPong()).start(); 
        } 
       public void run(){
           hit(Thread.currentThread().getId); 
        } 
   }Which two statements are true? (Choose two.)
A.   The output could be 8-1 7-2 8-2 7-1
B.   The output could be 7-1 7-2 8-1 6-1
C.   The output could be 8-1 7-1 7-2 8-2
D.   The output could be 8-1 8-2 7-1 7-2
答案:CD为什么会有两种结果啊 求高手解释

解决方案 »

  1.   

    A 7-2  7-1 并非合理的for 打印顺印
    B中 竟然有6/7/8  3个线程,是没可能的只有C/D的情况是有可能出现
      

  2.   

    A: 说明有7、8两个线程,但7-2不可能在7-1之前,因为同一个线程执行是有顺序性的。
    B: 有6、7、8三个线程,不可能。
    C/D:只要7-1在7-2之前、8-1在8-2之前的任意组合均可能。
      

  3.   

    A:因为线程是有顺序的所以A干掉
    B:因为只是开了两个线程所以B干掉
    为此就C||D了
      

  4.   

    A,答案是7-2  8-2  7-1是不可能出现的,因为不会先出现7-2 再 7-1 这不符合for循环逻辑
    如果是8-1 7-1 8-2 7-2则出是可能出现的。
    B,有三个线程出现是不可能的。
    C、D,都是可能出现,主要原因是由于synchronized是每一个对象都对应的一把锁。
    你这里:
       new Thread(new PingPong()).start(); 
       new Thread(new PingPong()).start();
    第一个线程里new PintPong()相当两个对象,第个对象都有自己对应的锁,没有达到synchronized的效果。楼主这里synchronized是没有作用的 ,相当于没有。
    如果把代码改成:
       public static void main(String[] args) {
    PingPong pp=new PingPong();
     new Thread(pp).start();
     new Thread(pp).start();
        }
    这样就实现了资源共享,答案也只有一个了。
    嘿嘿……