« Back
import java.util.Random; import java.util.concurrent.CountDownLatch; public class CountDownLatchTest { public static void main(String[] args) { CountDownLatch latch = new CountDownLatch(3); Random random = new Random(); Workers firstWorker = new Workers("firstWorker",latch, random.nextInt(5000)); Workers secondWorker = new Workers("secondWorker",latch, random.nextInt(5000)); Workers thirdWorker = new Workers("thirdWorker",latch, random.nextInt(5000)); new Thread(firstWorker, "WT-11").start(); new Thread(secondWorker, "WT-22").start(); new Thread(thirdWorker, "WT-33").start(); try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Finishing the Main Method"); } } import java.util.concurrent.CountDownLatch; public class Workers implements Runnable{ private CountDownLatch latch; private int delay; private String name; public Workers(String name,CountDownLatch latch, int delay) { this.latch = latch; this.delay = delay; this.name = name; } @Override public void run() { String name = Thread.currentThread().getName(); int delay = this.delay; System.out.println(name + " sleeping for " + delay + " milliseconds."); try { Thread.sleep(delay); } catch (InterruptedException e) { e.printStackTrace(); } this.latch.countDown(); System.out.println(name + " finished"); } }
WT-11 sleeping for 4755 milliseconds.
WT-22 sleeping for 1868 milliseconds.
WT-33 sleeping for 3363 milliseconds.
WT-22 finished
WT-33 finished
WT-11 finished
Finishing the Main Method
×
Report a Problem:
Description:
Submit