Java Programming - Threads - Discussion
Discussion Forum : Threads - Finding the output (Q.No. 17)
17.
What will be the output of the program?
public class Test
{
public static void main (String [] args)
{
final Foo f = new Foo();
Thread t = new Thread(new Runnable()
{
public void run()
{
f.doStuff();
}
});
Thread g = new Thread()
{
public void run()
{
f.doStuff();
}
};
t.start();
g.start();
}
}
class Foo
{
int x = 5;
public void doStuff()
{
if (x < 10)
{
// nothing to do
try
{
wait();
} catch(InterruptedException ex) { }
}
else
{
System.out.println("x is " + x++);
if (x >= 10)
{
notify();
}
}
}
}
Answer: Option
Explanation:
C is correct because the thread does not own the lock of the object it invokes wait() on. If the method were synchronized, the code would run without exception.
A, B are incorrect because the code compiles without errors.
D is incorrect because the exception is thrown before there is any output.
Discussion:
5 comments Page 1 of 1.
Nikhil said:
3 years ago
Both thread are waiting if we synchronized it.
Tarun said:
7 years ago
I guess there's an error with thread in "Test" class because if you observer carefully you can find ")" is somewhere at the end for the following line:
Thread t = new Thread(new Runnable()
i.e., at the end of that definition.
Am I correct?
Thread t = new Thread(new Runnable()
i.e., at the end of that definition.
Am I correct?
Karan Asthana said:
8 years ago
Shouldn't we either extend Thread class or implement Runnable interface to make the code errorfree?
Priya said:
1 decade ago
The program is not running anyway because of the FOO class. Compile time error.
Akk said:
1 decade ago
What if the method is synchronized? what will be the output then?
Both threads would be waiting right?
Both threads would be waiting right?
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers