gpt4 book ai didi

java - SCJP 主题章节问题

转载 作者:行者123 更新时间:2023-11-30 04:19:18 28 4
gpt4 key购买 nike

我无法理解 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(但我不明白为什么,如果有人能向我解释这个概念,我将非常感激)

最佳答案

考虑以下场景:

Thread 1 ID : 1
Thread 2 ID : 2
Following steps would take place:
Thread 1 gets CPU cycle and executes chat(1)
flag=1
x = 1 : since flag == 1 so yo is printed
Thread 1 is preempted by Thread 2
Thread 2 gets CPU cycle and executes chat(2)
flag = 1 (NOT 2 because flag==0 condition fails)
x = 1 : since flag!=2 so dude will be printed
x = 2 : since flag!=2 so dude will be printed
Thread 1 gets the CPU cycle
flag = 1
x = 2 : since flag == 1 so yo will be printed.


Hence the output is `yo dude dude yo`

关于java - SCJP 主题章节问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17513979/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com