• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Knute Snortum
  • paul wheaton
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Ron McLeod
  • Piet Souris
  • Ganesh Patekar
Bartenders:
  • Tim Holloway
  • Carey Brown
  • salvin francis

Need Help?

 
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
 
Sheriff
Posts: 9099
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
 
sunglasses are a type of coolness prosthetic. Check out the sunglasses on this tiny ad:
professionally read, modify and write PDF files from Java
https://products.aspose.com/pdf/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!