本文主要根据《Java程序员修炼之道》整理的代码笔记片段
示例代码(用于一半线程初始化后,才执行后续代码)
public class ProcessingThread extends Thread {
private final String ident;
private final CountDownLatch latch;
private static int MAX_THREADS = 17;
public ProcessingThread(String ident_, CountDownLatch cdl_) {
ident = ident_;
latch = cdl_;
}
public String getIdentifier() {
return ident;
}
public void initialize() {
latch.countDown();
}
public void run() {
try {
TimeUnit.SECONDS.sleep(1);//Java 5 写法
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
initialize();
System.out.println(ident + "|"+latch.getCount());
}
public static void main(String[] a) {
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();
//System.out.println("localhost:" + (9000 + i) + "|"+cdl.getCount());
}
cdl.await();//阻塞
System.out.println(cdl.getCount());
} catch (InterruptedException e) {
}finally{
}
}
}
结果:
localhost:9003|7
localhost:9010|5
localhost:9015|4
localhost:9012|6
localhost:9007|2
localhost:9014|7
localhost:9008|1
localhost:9011|3
localhost:9000|0
0
localhost:9002|0
localhost:9004|0
localhost:9006|0
localhost:9013|0
localhost:9001|0
localhost:9005|0
localhost:9009|0
localhost:9016|0