1.多线程的三种方式,实现runnable接口,继承thread类,实现callable接口,前面2个是没有返回值的,callable接口可以有返回值,所以个人角度觉得后者比较强大。但是注意点是在调用实现callable的构造方法时要用threadPoolExecutor.submit来执行,而前面的是用threadPoolExecutor.execute来执行
2.下面是一个线程池的应用场景——创建多个线程进行排序,此用例可直接拿去执行
3.线程池用完之后一定要记得关闭,否则会造成资源浪费。
package ceshi;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.*;
public class ThreadTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
aaa();
}
public static void aaa() throws ExecutionException, InterruptedException {
long start = System.currentTimeMillis();
List<Integer> age1 = new ArrayList<>();
List<Integer> age2 = new ArrayList<>();
List<Integer> age3 = new ArrayList<>();
age1.add(0);
age1.add(3);
age1.add(6);
age2.add(3333);
age2.add(4234234); age2.add(33); age3.add(2); age3.add(5); age3.add(6666666); age3.add(8);
List<List<Integer>> lists = new ArrayList<>();
lists.add(age1);
lists.add(age2);
lists.add(age3);
//核心线程数
int corePoolsize=5;
//最大线程数量
int maxThreadPoolsize=30;
//空闲时间
long keepAliveTime=600;
//队列
BlockingQueue<Runnable> workQueue = new SynchronousQueue<Runnable>();
//单位
TimeUnit unit=TimeUnit.SECONDS;
ThreadFactory threadFactory = Executors.defaultThreadFactory();
//拒绝策略
RejectedExecutionHandler rejectedExecutionHandler=new ThreadPoolExecutor.CallerRunsPolicy();
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolsize, maxThreadPoolsize, keepAliveTime, unit, workQueue, threadFactory, rejectedExecutionHandler);
for (List<Integer> age:lists){
Future submit = threadPoolExecutor.submit(new checkbyHand(age));
System.out.println(submit.get());
/* Collections.sort(age);
System.out.println(age.toString());*/
}
threadPoolExecutor.shutdown();
while (true) {//等待所有任务都执行结束
if (threadPoolExecutor.isTerminated()) {//所有的子线程都结束了
break;
}
}
System.out.println(System.currentTimeMillis()-start);
}
public static class checkbyHand implements Callable{
private List<Integer> age;
public checkbyHand(List<Integer> age) {
this.age = age;
}
@Override
public Object call() throws Exception {
Collections.sort(age);
return age;
}
}
}