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为什么会有两种结果啊 求高手解释
B中 竟然有6/7/8 3个线程,是没可能的只有C/D的情况是有可能出现
B: 有6、7、8三个线程,不可能。
C/D:只要7-1在7-2之前、8-1在8-2之前的任意组合均可能。
B:因为只是开了两个线程所以B干掉
为此就C||D了
如果是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();
}
这样就实现了资源共享,答案也只有一个了。
嘿嘿……