我在理解 SCJP 书籍 K&B 第 9 章(线程)中的以下程序时遇到问题
问题:
class Dudes{
static long flag = 0;
// insert code here
void chat(long id){
if(flag == 0)
flag = id;
for( int x = 1; x < 3; x++){
if( flag == id)
System.out.print("yo ");
else
System.out.print("dude ");
}
}
}
public class DudesChat implements Runnable{
static Dudes d;
public static void main( String[] args){
new DudesChat().go();
}
void go(){
d = new Dudes();
new Thread( new DudesChat()).start();
new Thread( new DudesChat()).start();
}
public void run(){
d.chat(Thread.currentThread().getId());
}
}
并给出这两个片段:
I. synchronized void chat (long id){
II. void chat(long id){
选项:
When fragment I or fragment II is inserted at line 5, which are true? (Choose all that apply.)
A. An exception is thrown at runtime
B. With fragment I, compilation fails
C. With fragment II, compilation fails
D. With fragment I, the ouput could be yo dude dude yo
E. With fragment I, the output could be dude dude yo yo
F. With fragment II, the output could be yo dude dude yo
官方答案是 F(但我不明白为什么,如果有人能解释一下这个概念,我将不胜感激)