Skip to content

Instantly share code, notes, and snippets.

@WenxiJin
Created May 13, 2019 11:15
Show Gist options
  • Save WenxiJin/706b8718fe9099cf4c3c669c880d7aeb to your computer and use it in GitHub Desktop.
Save WenxiJin/706b8718fe9099cf4c3c669c880d7aeb to your computer and use it in GitHub Desktop.
Main thread continues until worker thread finishes
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class CountDownLatchDemo {
public static void main(String args[]) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
Worker first = new Worker(10, latch, "1st-Worker");
first.start();
int i = 0;
while (true) {
System.out.println("Number:"+i++);
if (latch.await(1, TimeUnit.SECONDS)) {
break;
}
}
}
static class Worker extends Thread {
private int delay;
private CountDownLatch latch;
public Worker(int delay, CountDownLatch latch,
String name)
{
super(name);
this.delay = delay;
this.latch = latch;
}
@Override
public void run()
{
try
{
TimeUnit.SECONDS.sleep(delay);
latch.countDown();
System.out.println(Thread.currentThread().getName()
+ " finished");
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment