1.编写线程池工具类

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
35
36
37
38
39
40
41
42
43
44
45
46
47

public class ThreadUtils {

public static ExecutorService newFixedThreadPool() {
return new ThreadPoolExecutor(4,4, 10L, TimeUnit.MILLISECONDS,
new LinkedBlockingDeque<Runnable>(100),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.CallerRunsPolicy());
}

/**
* (1.8版本)使用线程池请求接口
*/
public static <T> void executerPool(List<T> list) throws InterruptedException {
ExecutorService executorService = newFixedThreadPool();
List<T> collect = list.stream().filter(l -> l instanceof Runnable).collect(Collectors.toList());
final CountDownLatch count=new CountDownLatch(collect.size());
for (T runnable : collect) {
Customers customers = (Customers) runnable;
customers.counts(count);
executorService.execute(customers);
}
count.await();
executorService.shutdown();
}

/**
* (1.7版本)使用线程池请求接口
*/
public static <T> void executerPool2(List<T> list) throws InterruptedException {
ExecutorService executorService = newFixedThreadPool();
List<Customers> runnables = new ArrayList<>();
for (T t : list) {
if(t instanceof Customers){
runnables.add((Customers) t);
}
}
final CountDownLatch count=new CountDownLatch(runnables.size());
for (Customers runnable : runnables) {
runnable.counts(count);
executorService.execute(runnable);
}
count.await();
executorService.shutdown();
}

}

2.定义接口ThreadFactorys和Customers

1
2
3
public interface ThreadFactorys{
public abstract void counts(CountDownLatch countDownLatch);
}
1
2
public interface Customers extends Runnable,ThreadFactorys{
}

3.继承Customers

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class InterfaceRunnable implements Customers{
private String name;
// 线程计数器
private CountDownLatch count;
public InterfaceRunnable(String name) {
this.name = name;
}
@Override
public void run() {
// 执行方法
System.out.println(name);
count.countDown();
}
@Override
public void counts(CountDownLatch countDownLatch) {
this.count = countDownLatch;
}
}

4.使用工具类进行调用(只需要把需要执行的类继承runnable方法,然后用list丢入工具类就行了)

1
2
3
4
5
6
7
8
9
public class ThreadController {
public static void main(String[] args) throws InterruptedException {
List<InterfaceRunnable> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
list.add(new InterfaceRunnable("方法调用:"+i));
}
ThreadUtils.executerPool(list);
}
}