Domanda

I am having problem to understand the following program in Chapter 9(threads) of SCJP book K&B

QUESTION:

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

And given these two fragments:

I. synchronized void chat (long id){  
             II. void chat(long id){  

OPTIONS:

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 

The Official Answer is F(But I cannot understand why, It would be really grateful if someone could explain me the concept)

È stato utile?

Soluzione

Consider the following scenario:

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`

Altri suggerimenti

if chat will be synchronized, output will be

yo yo dude dude 

There is one Object of Dudes, it is declared as static; We have one object, 2 threads and 1 synchronized method; if chat method will be synchronized, two threads can't access class synchronized method together.

if chat will not be synchronized, you will not detect answer (there will not be same answers, because two threads are invoked together so state is changing during the processes of each thread;

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top