我在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(但我不明白为什么,如果有人能解释我这个概念真的很感激)
答案 0 :(得分:2)
考虑以下情况:
主题1 ID:1
主题2 ID:2
以下步骤将采取 place:
线程1获得CPU周期并执行chat(1)
flag = 1
x = 1:由于flag == 1所以yo
被打印,因此线程1被抢占 通过线程2
线程2获得CPU周期并执行chat(2)
标志 = 1(NOT 2因为flag==0
条件失败)
x = 1:因为标志!= 2所以dude
将被打印
x = 2:因为标志!= 2所以dude
将被打印
线程1获得CPU周期
标志= 1×x = 2:因为flag == 1所以将打印yo
。
Hence the output is `yo dude dude yo`
答案 1 :(得分:0)
如果要同步聊天,则输出
yo yo dude dude
有一个Dudes对象,它被声明为静态;我们有一个对象,2个线程和1个同步方法;如果聊天方法将被同步,则两个线程不能一起访问类同步方法。
如果聊天不会同步,你将无法检测到答案(因为两个线程被一起调用,所以状态在每个线程的进程中都会发生变化;