Java Programming - Threads - Discussion

Discussion Forum : Threads - Finding the output (Q.No. 5)
5.
What will be the output of the program?
public class Q126 implements Runnable 
{ 
    private int x; 
    private int y; 

    public static void main(String [] args) 
    { 
        Q126 that = new Q126(); 
        (new Thread(that)).start( ); /* Line 8 */
        (new Thread(that)).start( ); /* Line 9 */
    } 
    public synchronized void run( ) /* Line 11 */
    { 
        for (;;) /* Line 13 */
        { 
            x++; 
            y++; 
            System.out.println("x = " + x + "y = " + y); 
        } 
    } 
}
An error at line 11 causes compilation to fail
Errors at lines 8 and 9 cause compilation to fail.
The program prints pairs of values for x and y that might not always be the same on the same line (for example, "x=2, y=1")
The program prints pairs of values for x and y that are always the same on the same line (for example, "x=1, y=1". In addition, each value appears once (for example, "x=1, y=1" followed by "x=2, y=2")
Answer: Option
Explanation:

The synchronized code is the key to answering this question. Because x and y are both incremented inside the synchronized method they are always incremented together. Also keep in mind that the two threads share the same reference to the Q126 object.

Also note that because of the infinite loop at line 13, only one thread ever gets to execute.

Discussion:
14 comments Page 2 of 2.

Preeti said:   9 years ago
@Rupesh Pawar.

It is ok to start twice as a new thread is created second time so both will act ss diff thread for the same object.

Pavan said:   9 years ago
@Abc.

That is the reference of the object Q126.

Narendra said:   8 years ago
I have executed code and two threads got a chance.

Thread-1x = 219751y = 219751
Thread-1x = 219752y = 219752
Thread-1x = 219753y = 219753
Thread-0x = 68569y = 68569
Thread-1x = 219754y = 219754
Thread-1x = 219755y = 219755
Thread-1x = 219756y = 219756
Thread-1x = 219757y = 219757
Thread-1x = 219758y = 219758
Thread-0x = 68570y = 68570
Thread-0x = 68571y = 68571

Can someone answer this?

Varsha said:   8 years ago
Start() method called two times with same object so it should give error.


Post your comments here:

Your comments will be displayed after verification.