我很难理解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(但我不明白为什么,如果有人能解释我的概念,我会很感激的)
发布于 2013-07-07 16:48:26
考虑以下情况:
线程1 ID :1 线程2 ID :2 将采取下列步骤: 线程1获取CPU周期并执行
chat(1)。 flag=1 X=1:因为标记== 1,所以yo被打印出来 线程1被线程2抢占 线程2获取CPU周期并执行chat(2)。 标志=1(而不是2,因为flag==0条件失败) X=1:空标志!=2,因此将打印dudeX=2:因为标志!=2所以dude将被打印出来 线程1获取CPU周期。 旗=1 X=2:因为标记== 1,所以yo将被打印。
Hence the output is `yo dude dude yo`发布于 2016-04-10 18:53:58
如果聊天将是同步的,输出将是
yo yo dude dude Dudes有一个对象,声明为静态;我们有一个对象,两个线程和一个同步方法;如果聊天方法被同步,两个线程不能一起访问类同步方法。
如果chat将不同步,您将不会检测到答案(不会有相同的答案,因为两个线程一起被调用,状态在每个线程的进程中发生变化;
https://stackoverflow.com/questions/17513979
复制相似问题