• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Need Help?

 
Jaffery Rab
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi
guys I need ur help
class Foo{
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();
System.out.println (sb1+" "+sb2); }
when I comppile this out put is nothing but I have options like
A)main will finish before starting threads
B)main will finish middle of one thread
C) main will finish after one thread
D)main will finish in middle of the second thread
E)main will finish after the second thread
which one is correct and offcourse why???
Thanx
Jaffery
 
Marilyn de Queiroz
Sheriff
Posts: 9067
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The answer is "It is impossible to predict."
Sometimes the main thread will finish before either of the other two threads and then you will see no output because both StringBuffers are initialized to no output.
Try this:

But the main thread may finish after the first new Thread, and the main thread may finish after both new Threads.
 
Jaffery Rab
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanx
I appreciate..
Jaffery
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic