class Test116
{
static final StringBuffer sb1 = new StringBuffer();
static final StringBuffer sb2 = new StringBuffer();
public static void main(String args[])
{
new Thread()
{
public void run()
{
synchronized(sb1)
{
sb1.append("A");
sb2.append("B");
}
}
}.start();
new Thread()
{
public void run()
{
synchronized(sb1)
{
sb1.append("C");
sb2.append("D");
}
}
}.start(); /* Line 28 */
System.out.println (sb1 + " " + sb2);
}
}
[A].
main() will finish before starting threads.
[B].
main() will finish in the middle of one thread.
[C].
main() will finish after one thread.
[D].
Cannot be determined.
Answer: Option B
Explanation:
Can you guarantee the order in which threads are going to run? No you can't. So how do you know what the output will be? The output cannot be determined.
I will try this program main thread always execute first after that other 2 thread execute. Please give me proper answer.
Poonam said:
(Mon, May 14, 2012 05:51:57 AM)
Can anyone explain me that how this output came. Because program executes from main and when the main get closed then why is it considering the lines outside the main.
Vishal Bhatt said:
(Mon, Jan 21, 2013 03:44:16 PM)
Only one thread is able to start. And output is AB.
So anyone can tell me about how to generate this output?