This week's giveaway is in the Spring forum.
We're giving away four copies of Learn Spring Security (video course) and have Eugen Paraschiv on-line!
See this thread for details.
Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Multi Threading

 
Garandi Garandi
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have the following code. Wants the main thread to wait until all other threads finishes execution.

Thank you
Garandi
 
David Weitzman
Ranch Hand
Posts: 1365
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The pure JFC solution is to store all the threads in a collection and have the main thread call join() on each one after they're all launched.

If you have util.concurrent in the classpath anyway you can use CountDown or in Java 5.0 CountDownLatch
[ August 04, 2004: Message edited by: David Weitzman ]
 
Rovas Kram
Ranch Hand
Posts: 135
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following modification has the main thread join each sub thread which will cause the main thread to wait for each sub thread to complete.

 
David Weitzman
Ranch Hand
Posts: 1365
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rovas, calling Thread.start() on one line and Thread.join() on the same thread a line later is not the most useful of patterns. It's like running the code without starting a thread, only there's a lot more overhead. I'm having trouble imagining circumstances when you'd ever want to join() immediately after start()ing. I guess it would keep the code from mucking with your ThreadLocals or throwing unexpected Errors/RuntimeExceptions at you.

I've added a word to my response above to clarify.
 
Rovas Kram
Ranch Hand
Posts: 135
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for pointing that out, David. The code that I submitted is not multi-threaded at all. As stated in the first reply(I'd use the user name if i could see - come on javaranch), I should put each sub-thread in a collection and then call join on each thread.
 
Garandi Garandi
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I should put each sub-thread in a collection and then call join on each thread.

I was wondering how to code it, if you can help me with it; that would be very useful.
Thank you in advance
Garandi
 
David Weitzman
Ranch Hand
Posts: 1365
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic