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 2 of 2.
Rupesh Pawar said:
1 decade ago
How come its fine to use start() method twice in this program. ?
Vasavi said:
1 decade ago
What is the use of synchronized keyword? what it work's here?
Alex said:
1 decade ago
Oh, I got it - they are int primitives, zero by default. :)
Pavan said:
9 years ago
@Abc.
That is the reference of the object Q126.
That is the reference of the object Q126.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers