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);
}
}
}
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 1 of 2.
Alex said:
1 decade ago
Oh, I got it - they are int primitives, zero by default. :)
Alex said:
1 decade ago
How it will work D-way if 'x' and 'y' are never initialized and are private, so there's no access to set them out of this class?
Not to mention comma and space (", ") appeared in your answer in example output.
Thanks, Alex.
Not to mention comma and space (", ") appeared in your answer in example output.
Thanks, Alex.
Vasavi said:
1 decade ago
What is the use of synchronized keyword? what it work's here?
Vasavi said:
1 decade ago
Why here no error will come? because here we cal start() method 2 times with saMe object.
Austin said:
1 decade ago
Due to the header of run method, the run() method of interface runnable will not be overridden. Therefore, there will be method name mismatch, i.e., it will be neither overloaded or overridden.
Hence it should give compilation error.
Hence it should give compilation error.
Savitha said:
1 decade ago
Austin, synchronized keyword is not part of the method signature. So it can be added for overriding a method. Also, a synchronized method can be overridden without using a synchronized keyword. So you would not get a compilation error for the above code
As there is a infinite loop, the first thread enters execution , keeps holding the lock, so the next thread never gets its turn.
As there is a infinite loop, the first thread enters execution , keeps holding the lock, so the next thread never gets its turn.
Suvarna said:
1 decade ago
I have executed this code. I found exception constructor thread is undefined.
Dota 2 said:
1 decade ago
Java should have initial value for each variable. On this code x and y don't have it.
Rupesh Pawar said:
1 decade ago
How come its fine to use start() method twice in this program. ?
ABC said:
1 decade ago
How come it does not give an error?
There is no that keyword in JAVA!
There is no that keyword in JAVA!
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers