This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Threads and Synchronization and the fly likes CountDownLatch how its work Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "CountDownLatch how its work" Watch "CountDownLatch how its work" New topic
Author

CountDownLatch how its work

vivek dhiman
Ranch Hand

Joined: Aug 05, 2011
Posts: 111

Hi

I have following code which i want to check with CountDownLatch. I have two threads, one which prints odd numbers and second which prints even numbers. I want odd numbers should print first then even, but output seems alternative, first even then odd..... Also last statement not getting print "====END====". Please Suggest.



Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 41052
    
  43
You misunderstand what CountDownLatch does. It causes the thread that calls await() to wait until countDown() has been called as many times as specified in the constructor. So in this case, the main thread will wait until countDown() has been called twice - which will never happen because it is called only once.

I'm not sure why you think it would somehow cause one thread to run entirely before the other - calling sleep on the ODD thread will cause control to be transferred to some other thread, and since the main thread is waiting, the other one will likely be the EVEN thread (and vice versa).


Ping & DNS - my free Android networking tools app
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4164
    
  21

What Ulf said. You should not use sleep() to control swapping between threads, you need locks and conditions (or synchronized locks and wait() notify() or similar construct). Also, your condition for determining odd or even is reversed. This is inside your 'Odd' thread: if (i % 2 == 0), but mod returns 0 when the value is evenly divisible by the second parameter. So this would be true for Even not Odd.


Steve
vivek dhiman
Ranch Hand

Joined: Aug 05, 2011
Posts: 111

Thanks, i am trying to implement the join() behavior but without using join() method. So how can i implement this.
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 41052
    
  43
Why do you want to avoid using a feature if it does what you want to accomplish?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: CountDownLatch how its work
 
Similar Threads
Thread question
How can I serialize thread handling with Java 5's java.util.concurrent package?
start() method in Thread
After notify()
Print Odd and even number in sequence with using two threads