有时,为了程序的性能,我们有必要对程序中的for循环(含有sql/rpc操作)进行并发处理,要求是并发处理完之后才能继续执行主线程。现给出如下两种方案:
1. countdownlatch

package com.itlong.whatsmars.base.sync;
import java.util.concurrent.countdownlatch;
/**
* created by shenhongxi on 2016/8/12.
*/
public class countdownlatchtest {
public static void main(string[] args) {
countdownlatch latch = new countdownlatch(3);
long start = system.currenttimemillis();
for (int i = 0; i < 3; i++) {
new thread(new subrunnable(i, latch)).start();
}
try {
latch.await();
} catch (interruptedexception e) {
e.printstacktrace();
system.out.println(system.currenttimemillis() - start);
system.out.println("main finished");
}
static class subrunnable implements runnable {
private int id = -1;
private countdownlatch latch;
subrunnable(int id, countdownlatch latch) {
this.id = id;
this.latch = latch;
@override
public void run() {
try {
thread.sleep(3000);
system.out.println(string
.format("sub thread %d finished", id));
} catch (interruptedexception e) {
e.printstacktrace();
} finally {
latch.countdown();
}
}
countdownlatch用队列来存放任务,主要是一个构造器和两个方法,相关代码这里不予赘述。countdownlatch很贴合我们的要求,但没用到线程池,而且latch是只提供了计数功能然后子线程的逻辑有没有可能会在主线程逻辑之后执行??,综合考虑,我推荐下面的这种方案。
2. executorservice

import java.util.arraylist;
import java.util.list;
import java.util.concurrent.callable;
import java.util.concurrent.executorservice;
import java.util.concurrent.executors;
public class callabletest {
public static void main(string[] args) throws exception {
executorservice pool = executors.newfixedthreadpool(3);
list<callable<void>> subs = new arraylist<callable<void>>();
subs.add(new subcallable(i));
pool.invokeall(subs);
} finally {
pool.shutdown();
static class subcallable implements callable<void> {
public subcallable(int id) {
public void call() throws exception {
.format("child thread %d finished", id));
return null;
abstractexecutorservice

public <t> list<future<t>> invokeall(collection<? extends callable<t>> tasks)
throws interruptedexception {
if (tasks == null)
throw new nullpointerexception();
list<future<t>> futures = new arraylist<future<t>>(tasks.size());
boolean done = false;
for (callable<t> t : tasks) {
runnablefuture<t> f = newtaskfor(t);
futures.add(f);
execute(f);
for (future<t> f : futures) {
if (!f.isdone()) {
try {
f.get();
} catch (cancellationexception ignore) {
} catch (executionexception ignore) {
}
}
done = true;
return futures;
if (!done)
for (future<t> f : futures)
f.cancel(true);
接下来我做了个join的试验,发现同样可以达到目的,但不推荐此法。

* 子线程与主线程是顺序执行的,各子线程之间还是异步的
public class jointest {
thread t1 = new thread(new subrunnable(0));
thread t2 = new thread(new subrunnable(1));
thread t3 = new thread(new subrunnable(2));
t1.start();
t2.start();
t3.start();
t1.join();
t2.join();
t3.join();
subrunnable(int id) {
system.out.println("hi, i'm id-" + id);
thread.sleep(9000);
最后,我们顺便提下org.springframework.scheduling.concurrent.threadpooltaskexecutor

public class threadpooltaskexecutor extends executorconfigurationsupport implements schedulingtaskexecutor {
private final object poolsizemonitor = new object();
private int corepoolsize = 1;
private int maxpoolsize = integer.max_value;
private int keepaliveseconds = 60;
private boolean allowcorethreadtimeout = false;
private int queuecapacity = integer.max_value;
private threadpoolexecutor threadpoolexecutor;
/**
* set the threadpoolexecutor's core pool size.
* default is 1.
* <p><b>this setting can be modified at runtime, for example through jmx.</b>
*/
public void setcorepoolsize(int corepoolsize) {
synchronized (this.poolsizemonitor) {
this.corepoolsize = corepoolsize;
if (this.threadpoolexecutor != null) {
this.threadpoolexecutor.setcorepoolsize(corepoolsize);
* return the threadpoolexecutor's core pool size.
public int getcorepoolsize() {
return this.corepoolsize;
看到我们熟悉的threadpoolexecutor之后,我们瞬间明白了一切。
另外我们脑补下几个接口/类的关系

public interface executorservice extends executor {
<t> list<future<t>> invokeall(collection<? extends callable<t>> tasks)
throws interruptedexception;
public interface executor {
void execute(runnable command);
public abstract class abstractexecutorservice implements executorservice{
public <t> list<future<t>> invokeall(collection<? extends callable<t>> tasks) {
// ...
}
public class threadpoolexecutor extends abstractexecutorservice {
public threadpoolexecutor(int corepoolsize,
int maximumpoolsize,
long keepalivetime,
timeunit unit,
blockingqueue<runnable> workqueue) {
this(corepoolsize, maximumpoolsize, keepalivetime, unit, workqueue,
executors.defaultthreadfactory(), defaulthandler);
原文链接:[http://wely.iteye.com/blog/2317944]