Reputation: 2731
I am creating a simple Java8 concurrency CountDownLatch example. I am creating a latch of size 2 and start 2 threads and call await on the latch. See the below example.
package CountDownLatchExample;
import java.util.concurrent.CountDownLatch;
public class CountDownLatchExample {
static final CountDownLatch latch = new CountDownLatch(2);
public static void main(String[] args) throws InterruptedException {
MyThread thread = new MyThread(latch);
new Thread(thread).start();
new Thread(thread).start();
latch.await();
System.out.println(Thread.currentThread().getName() + " done.");
}
}
class MyThread implements Runnable {
CountDownLatch latch;
MyThread(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
latch.countDown();
System.out.println(Thread.currentThread().getName() + " completed.");
}
}
I am expecting Thread-0, Thread-1 to complete before main completes (based on sysout) consistently. However when I execute the program sometimes the "main done" message prints before even the Thread-1 completes. Is my implementation or my understanding is incorrect? Please suggest.
Output:
> Task :CountDownLatchExample.main()
Thread-0 completed.
main done.
Thread-1 completed.
Upvotes: 0
Views: 1186
Reputation: 997
When I executed, I am getting this output:
Thread-0 completed.
Thread-1 completed.
main done.
The context switch between thread can also happend after the call to latch.countDown(); in the run method. I suggest you modify the run method as below to get desired and consistent result.
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " completed.");
latch.countDown();
}
Upvotes: 2