Java Programming - Threads - Discussion

16. 

What will be the output of the program?

public class Test107 implements Runnable 
{ 
    private int x; 
    private int y; 

    public static void main(String args[]) 
    {
        Test107 that = new Test107(); 
        (new Thread(that)).start(); 
        (new Thread(that)).start(); 
    } 
    public synchronized void run() 
    {
        for(int i = 0; i < 10; i++) 
        { 
            x++; 
            y++; 
            System.out.println("x = " + x + ", y = " + y); /* Line 17 */
        } 
    } 
} 

[A]. Compilation error.
[B]. Will print in this order: x = 1 y = 1 x = 2 y = 2 x = 3 y = 3 x = 4 y = 4 x = 5 y = 5... but the output will be produced by both threads running simultaneously.
[C]. Will print in this order: x = 1 y = 1 x = 2 y = 2 x = 3 y = 3 x = 4 y = 4 x = 5 y = 5... but the output will be produced by first one thread then the other. This is guaranteed by the synchronised code.
[D]. Will print in this order x = 1 y = 2 x = 3 y = 4 x = 5 y = 6 x = 7 y = 8...

Answer: Option C

Explanation:

Both threads are operating on the same instance variables. Because the code is synchronized the first thread will complete before the second thread begins. Modify line 17 to print the thread names:

System.out.println(Thread.currentThread().getName() + " x = " + x + ", y = " + y);


Faten Yahiaoui said: (Feb 3, 2015)  
Actually the variables x and y haven't been initialized.

James said: (Feb 8, 2016)  
It won't even compile since there is no such keyword as "that".

Sahil said: (Jul 28, 2016)  
x and y are not initialized, so it will give a compilation error.

Rochelle said: (Mar 16, 2017)  
Compilation error because the class implements runnable and it must implements the required method which is public void run().

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.