1

SCJP book K&B の Chapter 9(threads) にある次のプログラムを理解するのに問題があります

質問:

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());  
    }  
} 

そして、次の 2 つのフラグメントが与えられます。

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です(しかし、理由がわかりません。誰かが私に概念を説明してくれると本当にありがたいです)

4

2 に答える 2

0

チャットが同期される場合、出力は

yo yo dude dude 

Dudes のオブジェクトが 1 つあり、静的として宣言されています。1 つのオブジェクト、2 つのスレッド、1 つの同期メソッドがあります。チャット メソッドが同期される場合、2 つのスレッドが同時にクラス同期メソッドにアクセスすることはできません。

チャットが同期されない場合、回答が検出されません (2 つのスレッドが一緒に呼び出され、各スレッドのプロセス中に状態が変化するため、同じ回答はありません。

于 2016-04-10T18:53:58.277 に答える