• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

CountDownLatch how its work

 
vivek dhiman
Ranch Hand
Posts: 152
Netbeans IDE Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Rancher
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
Steve Luke
Bartender
Posts: 4181
21
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
vivek dhiman
Ranch Hand
Posts: 152
Netbeans IDE Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, i am trying to implement the join() behavior but without using join() method. So how can i implement this.
 
Ulf Dittmer
Rancher
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why do you want to avoid using a feature if it does what you want to accomplish?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic