Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

Can someone please explain this java program ? It is an implementation of Executors.?

import java.util.concurrent.CountDownLatch;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

class SimpExec {

public static void main(String args[]) {

CountDownLatch cdl = new CountDownLatch(5);

CountDownLatch cdl2 = new CountDownLatch(5);

CountDownLatch cdl3 = new CountDownLatch(5);

CountDownLatch cdl4 = new CountDownLatch(5);

ExecutorService es = Executors.newFixedThreadPool(2);

es.execute(new MyThread(cdl, "A"));

es.execute(new MyThread(cdl2, "B"));

es.execute(new MyThread(cdl3, "C"));

es.execute(new MyThread(cdl4, "D"));

try {

cdl.await();

cdl2.await();

cdl3.await();

cdl4.await();

} catch (InterruptedException exc) {

System.out.println(exc);

}

es.shutdown();

}

}

class MyThread implements Runnable {

String name;

CountDownLatch latch;

MyThread(CountDownLatch c, String n) {

latch = c;

name = n;

new Thread(this);

}

public void run() {

for (int i = 0; i < 5; i++) {

latch.countDown();

}

}

}

1 Answer

Relevance
  • 1 decade ago
    Favorite Answer

    Thanks for your question, I was not even aware of this addition since Java 1.5 to the java.util.concurrent API.

    The API docs list ExecutorService as the interface for CountdownLatch(). CountdownLatch is Factory that adds methods. The most useful, it seems, is with a queue of threads is the queue is maintained even if the thread beats the clock assigned to it.

    I changed the void run(). See if this helps you

    public void run() {

    for (int i = 0; i < 5; i++) {

    System.out.printf("%s : %s%n", latch.getClass()

    .getSimpleName(),

    this.name);

    latch.countDown();

    }

    }

    But, basically, you now have a Thread, with a pointer( or variable name), and you can add attributes, and like I mentioned, keep the order of execution. Pretty cool.

    Now, all I have to do is utilize it.

Still have questions? Get your answers by asking now.