java线程池使用例子

1.invokeAll

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
ExecutorService exec = Executors.newFixedThreadPool(threadNum);

List<Callable<Integer>> tasks = new ArrayList<Callable<Integer>>();
Callable<Integer> task = null;
List<List> cutList = null;

// 确定每条线程的数据
for (int i = 0; i < threadNum; i++) {
if (i == threadNum - 1) {
if (special) {
break;
}
cutList = jsonList.subList(threadSize * i, dataSize);
} else {
cutList = jsonList.subList(threadSize * i, threadSize * (i + 1));
}
final List<List> listStr = cutList;
task =
new Callable<Integer>() {

@Override
public Integer call() throws Exception {
··· 代码 ···
return 1;
}
};
// 这里提交的任务容器列表和返回的Future列表存在顺序对应的关系
tasks.add(task);
}

exec.invokeAll(tasks);
exec.shutdown();

2.submit

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
ExecutorService exec = Executors.newFixedThreadPool(threadNum);

List<Runnable> tasks = new ArrayList<>();
Runnable task = null;
List<List> cutList = null;

// 确定每条线程的数据
for (int i = 0; i < threadNum; i++) {
if (i == threadNum - 1) {
if (special) {
break;
}
cutList = jsonList.subList(threadSize * i, dataSize);
} else {
cutList = jsonList.subList(threadSize * i, threadSize * (i + 1));
}
final List<List> listStr = cutList;
task =
new Runnable() {
@Override
public void run() {
··· 代码 ···
}
};
// 这里提交的任务容器列表和返回的Future列表存在顺序对应的关系
exec.submit(task);
}

exec.shutdown();
while (true) {
if (exec.isTerminated()) {
return resInfo;
}
}

3.execute

1
2
3
4
5
6
7
8
9
10
11
12
ExecutorService es = Executors.newFixedThreadPool(10);        
es.execute(new Thread());//执行子线程任务
try {
es.shutdown();
if(!es.awaitTermination(20,TimeUnit.SECONDS)){//20S
System.out.println(" 到达指定时间,还有线程没执行完,不再等待,关闭线程池!");
es.shutdownNow();
}
} catch (Throwable e) { // TODO Auto-generated catch block
es.shutdownNow();
e.printStackTrace();
}