This is achieved by providing an int value (the count) when constructing a new
instance of CountDownLatch. After that point, two methods are used to control the
latch: countDown() and await(). The former reduces the count by 1, and the latter
causes the calling thread to wait until the count reaches 0 (it does nothing if the count
is already 0 or less). This simple mechanism allows the minimum preparation pattern
to be easily deployed.
import java.util.HashSet; import java.util.Set; import java.util.concurrent.CountDownLatch; public class ProcessingThreadTest { public static final int MAX_THREADS = 10; public static class ProcessingThread extends Thread { private final String ident; private final CountDownLatch latch; public ProcessingThread(String ident_, CountDownLatch cdl_) { ident = ident_; latch = cdl_; } public String getIdentifier() { return ident; } public void initialize() { latch.countDown(); try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } } @Override public void run() { initialize(); while(true){ System.out.println(getIdentifier()); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } } } public static void main(String[] args) { final int quorum = 1 + (int) (MAX_THREADS / 2); final CountDownLatch cdl = new CountDownLatch(quorum); final Set<ProcessingThread> nodes = new HashSet<>(); try { for (int i = 0; i < MAX_THREADS; i++) { ProcessingThread local = new ProcessingThread("localhost:" + (9000 + i), cdl); nodes.add(local); local.start(); Thread.sleep(1000); System.out.println("-----------------"); } } catch (InterruptedException e) { } finally { } } }
No comments:
Post a Comment