线程池: 提供了一个线程队列,队列中保存着所有等待状态的线程。避免了创建与销毁额外开销,提高了响应的速度。
java.util.concurrent.Executor:负责线程的使用与调度的根接口
工具类:java.util.concurrent.Executors
创建一个继承Runnable接口的类
// 测试的继承Runnable接口的类
class RunDemo implements Runnable{
@Override
public void run() {
for(int i=0;i<5;i++){
System.out.println(Thread.currentThread().getName()+"==>"+i);
}
}
}
测试主函数:
ExecutorService pool = Executors.newFixedThreadPool(3);//创建指定三个线程的线程池
for(int i=0;i<3;i++){
pool.submit(new RunDemo());
}
pool.shutdown();//当前任务执行完之后关闭
// pool.shutdownNow();//强制关闭
//使用callable普通任务,创建匿名内部类,测试submit
List<Future<Integer>>list = new ArrayList<Future<Integer>>();
for (int i = 0; i < 10; i++) {
Future<Integer> future = pool.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
int sum=0;
for(int j=0;j<100;j++){
sum+=j;
}
return sum;
}
});
list.add(future);
}
for(Future<Integer>future:list){
try {
System.out.println(future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
pool.shutdown();
ScheduledExecutorService pool2 = Executors.newScheduledThreadPool(3);
//使用callable定时任务
for(int i=0;i<5;i++){
Future<Integer> result = pool2.schedule(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
int num = new Random().nextInt(100);//100以内的随机数
return num;
}
}, 1,TimeUnit.SECONDS);
try {
System.out.println(result.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
pool2.shutdown();
Fork/Join 框架:就是在必要的情况下,将一个大任务,进行拆分(fork)成若干个小任务(拆到不可再拆时),再将一个个的小任务运算的结果进行 join 汇总。
class CaculatorForkAndJoin extends RecursiveTask<Long>{
/**
* 创建serialVersionUID
*/
private static final long serialVersionUID = 1L;
private long start;
private long end;
private static final long THURSHOLD = 10000L; //临界值
CaculatorForkAndJoin(long start,long end){
this.start = start;
this.end = end;
}
//重写方法
@Override
protected Long compute() {
long length = end - start;
if(length <= THURSHOLD){
long sum = new Long(0);
for(long i = start;i<=end;i++){
sum+=i;
}
return sum;
}else{
//中间值
long mid = (start + end ) / 2;
CaculatorForkAndJoin left = new CaculatorForkAndJoin(start, mid);
left.fork();//进行拆分,同时压入现线程队列
CaculatorForkAndJoin right = new CaculatorForkAndJoin(mid+1, end);
right.fork();//进行拆分,同时压入现线程队列
return left.join()+right.join();
}
}
}
测试输出:
public static void main(String[] args) {
long start = System.currentTimeMillis();
//创建 线程池
ForkJoinPool pool = new ForkJoinPool();
//创建任务
CaculatorForkAndJoin task = new CaculatorForkAndJoin(0L,100000000L);
//添加任务到线程池,获得返回值
long sum = pool.invoke(task);
long end = System.currentTimeMillis();
System.out.println(sum+"spend:"+(end - start));
}
5000000050000000spend:1498