Java Programming - Threads - Discussion
Discussion Forum : Threads - Finding the output (Q.No. 16)
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 */
}
}
}
Answer: Option
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);
Discussion:
5 comments Page 1 of 1.
Tom said:
7 years ago
The second thread might call run() as first.
So "the first thread will complete before the second thread begins." is not always true.
So "the first thread will complete before the second thread begins." is not always true.
Rochelle said:
8 years ago
Compilation error because the class implements runnable and it must implements the required method which is public void run().
Sahil said:
8 years ago
x and y are not initialized, so it will give a compilation error.
(1)
James said:
9 years ago
It won't even compile since there is no such keyword as "that".
Faten Yahiaoui said:
10 years ago
Actually the variables x and y haven't been initialized.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers