CountDownLatch with return value

本文介绍了一种利用Java中的CountDownLatch来同步多个线程并收集它们执行结果的方法。通过实例演示如何创建和使用CountDownLatch来确保所有任务完成后再进行下一步操作。
對於這一篇(http://olife.iteye.com/blog/673659)
我們來個衍生...

有些時候,thread撒出去後,
我們會想將他們的結果收集起來再進行下一個步驟,
這時候,我們可以在撒thread的時候,
將一個收集結果的vector或是collection一併丟進去,
當thread執行完,就將結果丟進這個vector或是collection裡面,
以達到收集每個thread的執行結果之效。

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.Vector;

public class CountDownLatchDemo {

private static final int PLAY_AMOUNT = 10;

public static void main(String[] args) {

/*
* 比賽開始:只要裁判說開始,那麼所有跑步選手就可以開始跑了
* */
CountDownLatch begin = new CountDownLatch(1);
Vector<Integer> vect = new Vector<Integer>();

/*
* 每個隊員跑到末尾時,則報告一個到達,所有人員都到達時,則比賽結束
* */
CountDownLatch end = new CountDownLatch(PLAY_AMOUNT);
Player[] plays = new Player[PLAY_AMOUNT];
for(int i = 0;i<PLAY_AMOUNT;i++) {
plays[i] = new Player(i+1,begin,end,vect);
}
ExecutorService exe = Executors.newFixedThreadPool(PLAY_AMOUNT);
for(Player p : plays) {//各就各位
exe.execute(p);
}
System.out.println("比賽開始");
begin.countDown();//宣布開始
try {
end.await();//等待結束
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("比賽結束");
}

//注意:此時main線程已經要結束了,但是exe線程如果不關閉是不會結束的
exe.shutdown();
for (int i = 0 ; i < vect.size() ;i++) {
System.out.println(vect.get(i));
}
}

}


class Player implements Runnable {

private int id;

private CountDownLatch begin;

private CountDownLatch end;
private Vector<Integer> vect;

public Player(int id, CountDownLatch begin, CountDownLatch end,Vector<Integer> vect) {
super();
this.id = id;
this.begin = begin;
this.end = end;
this.vect = vect;
}

public void run() {
try {
begin.await();//必須等到裁判countdown到0的時候才開始
Thread.sleep((long)Math.random()*100);//模擬跑步需要的時間
vect.add(id);
System.out.println("Play "+id+" has arrived. ");

} catch (InterruptedException e) {
e.printStackTrace();
} finally {
end.countDown();//向評委報告跑到終點了
}
}
}
分析一下这个里面的sleep函数,是什么意思// // Source code recreated from a .class file by IntelliJ IDEA // (powered by FernFlower decompiler) // package cn.hutool.core.thread; import cn.hutool.core.util.RuntimeUtil; import java.util.concurrent.Callable; import java.util.concurrent.CompletionService; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; public class ThreadUtil { public ThreadUtil() { } public static ExecutorService newExecutor(int corePoolSize) { ExecutorBuilder builder = ExecutorBuilder.create(); if (corePoolSize > 0) { builder.setCorePoolSize(corePoolSize); } return builder.build(); } public static ExecutorService newExecutor() { return ExecutorBuilder.create().useSynchronousQueue().build(); } public static ExecutorService newSingleExecutor() { return ExecutorBuilder.create().setCorePoolSize(1).setMaxPoolSize(1).setKeepAliveTime(0L).buildFinalizable(); } public static ThreadPoolExecutor newExecutor(int corePoolSize, int maximumPoolSize) { return ExecutorBuilder.create().setCorePoolSize(corePoolSize).setMaxPoolSize(maximumPoolSize).build(); } public static ExecutorService newExecutor(int corePoolSize, int maximumPoolSize, int maximumQueueSize) { return ExecutorBuilder.create().setCorePoolSize(corePoolSize).setMaxPoolSize(maximumPoolSize).setWorkQueue(new LinkedBlockingQueue(maximumQueueSize)).build(); } public static ThreadPoolExecutor newExecutorByBlockingCoefficient(float blockingCoefficient) { if (!(blockingCoefficient >= 1.0F) && !(blockingCoefficient < 0.0F)) { int poolSize = (int)((float)RuntimeUtil.getProcessorCount() / (1.0F - blockingCoefficient)); return ExecutorBuilder.create().setCorePoolSize(poolSize).setMaxPoolSize(poolSize).setKeepAliveTime(0L).build(); } else { throw new IllegalArgumentException("[blockingCoefficient] must between 0 and 1, or equals 0."); } } public static ExecutorService newFixedExecutor(int nThreads, String threadNamePrefix, boolean isBlocked) { return newFixedExecutor(nThreads, 1024, threadNamePrefix, isBlocked); } public static ExecutorService newFixedExecutor(int nThreads, int maximumQueueSize, String threadNamePrefix, boolean isBlocked) { return newFixedExecutor(nThreads, maximumQueueSize, threadNamePrefix, (isBlocked ? RejectPolicy.BLOCK : RejectPolicy.ABORT).getValue()); } public static ExecutorService newFixedExecutor(int nThreads, int maximumQueueSize, String threadNamePrefix, RejectedExecutionHandler handler) { return ExecutorBuilder.create().setCorePoolSize(nThreads).setMaxPoolSize(nThreads).setWorkQueue(new LinkedBlockingQueue(maximumQueueSize)).setThreadFactory(createThreadFactory(threadNamePrefix)).setHandler(handler).build(); } public static void execute(Runnable runnable) { GlobalThreadPool.execute(runnable); } public static Runnable execAsync(Runnable runnable, boolean isDaemon) { Thread thread = new Thread(runnable); thread.setDaemon(isDaemon); thread.start(); return runnable; } public static <T> Future<T> execAsync(Callable<T> task) { return GlobalThreadPool.submit(task); } public static Future<?> execAsync(Runnable runnable) { return GlobalThreadPool.submit(runnable); } public static <T> CompletionService<T> newCompletionService() { return new ExecutorCompletionService(GlobalThreadPool.getExecutor()); } public static <T> CompletionService<T> newCompletionService(ExecutorService executor) { return new ExecutorCompletionService(executor); } public static CountDownLatch newCountDownLatch(int threadCount) { return new CountDownLatch(threadCount); } public static Thread newThread(Runnable runnable, String name) { Thread t = newThread(runnable, name, false); if (t.getPriority() != 5) { t.setPriority(5); } return t; } public static Thread newThread(Runnable runnable, String name, boolean isDaemon) { Thread t = new Thread((ThreadGroup)null, runnable, name); t.setDaemon(isDaemon); return t; } public static boolean sleep(Number timeout, TimeUnit timeUnit) { try { timeUnit.sleep(timeout.longValue()); return true; } catch (InterruptedException var3) { return false; } } public static boolean sleep(Number millis) { return millis == null ? true : sleep(millis.longValue()); } public static boolean sleep(long millis) { if (millis > 0L) { try { Thread.sleep(millis); } catch (InterruptedException var3) { return false; } } return true; } public static boolean safeSleep(Number millis) { return millis == null ? true : safeSleep(millis.longValue()); } public static boolean safeSleep(long millis) { long spendTime; for(long done = 0L; done >= 0L && done < millis; done += spendTime) { long before = System.currentTimeMillis(); if (!sleep(millis - done)) { return false; } spendTime = System.currentTimeMillis() - before; if (spendTime <= 0L) { break; } } return true; } public static StackTraceElement[] getStackTrace() { return Thread.currentThread().getStackTrace(); } public static StackTraceElement getStackTraceElement(int i) { StackTraceElement[] stackTrace = getStackTrace(); if (i < 0) { i += stackTrace.length; } return stackTrace[i]; } public static <T> ThreadLocal<T> createThreadLocal(boolean isInheritable) { return (ThreadLocal<T>)(isInheritable ? new InheritableThreadLocal() : new ThreadLocal()); } public static <T> ThreadLocal<T> createThreadLocal(Supplier<? extends T> supplier) { return ThreadLocal.withInitial(supplier); } public static ThreadFactoryBuilder createThreadFactoryBuilder() { return ThreadFactoryBuilder.create(); } public static ThreadFactory createThreadFactory(String threadNamePrefix) { return ThreadFactoryBuilder.create().setNamePrefix(threadNamePrefix).build(); } public static void interrupt(Thread thread, boolean isJoin) { if (null != thread && !thread.isInterrupted()) { thread.interrupt(); if (isJoin) { waitForDie(thread); } } } public static void waitForDie() { waitForDie(Thread.currentThread()); } public static void waitForDie(Thread thread) { if (null != thread) { boolean dead = false; do { try { thread.join(); dead = true; } catch (InterruptedException var3) { } } while(!dead); } } public static Thread[] getThreads() { return getThreads(Thread.currentThread().getThreadGroup().getParent()); } public static Thread[] getThreads(ThreadGroup group) { Thread[] slackList = new Thread[group.activeCount() * 2]; int actualSize = group.enumerate(slackList); Thread[] result = new Thread[actualSize]; System.arraycopy(slackList, 0, result, 0, actualSize); return result; } public static Thread getMainThread() { for(Thread thread : getThreads()) { if (thread.getId() == 1L) { return thread; } } return null; } public static ThreadGroup currentThreadGroup() { SecurityManager s = System.getSecurityManager(); return null != s ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); } public static ThreadFactory newNamedThreadFactory(String prefix, boolean isDaemon) { return new NamedThreadFactory(prefix, isDaemon); } public static ThreadFactory newNamedThreadFactory(String prefix, ThreadGroup threadGroup, boolean isDaemon) { return new NamedThreadFactory(prefix, threadGroup, isDaemon); } public static ThreadFactory newNamedThreadFactory(String prefix, ThreadGroup threadGroup, boolean isDaemon, Thread.UncaughtExceptionHandler handler) { return new NamedThreadFactory(prefix, threadGroup, isDaemon, handler); } public static void sync(Object obj) { synchronized(obj) { try { obj.wait(); } catch (InterruptedException var4) { } } } public static ConcurrencyTester concurrencyTest(int threadSize, Runnable runnable) { return (new ConcurrencyTester(threadSize)).test(runnable); } public static ScheduledThreadPoolExecutor createScheduledExecutor(int corePoolSize) { return new ScheduledThreadPoolExecutor(corePoolSize); } public static ScheduledThreadPoolExecutor schedule(ScheduledThreadPoolExecutor executor, Runnable command, long initialDelay, long period, boolean fixedRateOrFixedDelay) { return schedule(executor, command, initialDelay, period, TimeUnit.MILLISECONDS, fixedRateOrFixedDelay); } public static ScheduledThreadPoolExecutor schedule(ScheduledThreadPoolExecutor executor, Runnable command, long initialDelay, long period, TimeUnit timeUnit, boolean fixedRateOrFixedDelay) { if (null == executor) { executor = createScheduledExecutor(2); } if (fixedRateOrFixedDelay) { executor.scheduleAtFixedRate(command, initialDelay, period, timeUnit); } else { executor.scheduleWithFixedDelay(command, initialDelay, period, timeUnit); } return executor; } }
最新发布
11-05
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值