0. 概述
多线程编程一直是面试的重点,关于多线程的线程池的用法、线程的创建、线程间的数据传递将通过本例进行说明。
1. 创建线程的方法
- 继承Thread类
- 实现Runnable接口(实现run方法)
- 实现Callable接口(实现call()方法)
2. 启动线程的方法
- 如果是继承Thread类,直接new实例,调用start()方法,如new ThreadTask().start();
- 如果是实现了Runnable,通过new Thread(Runnable r).start()方法启动,其中r为实现了Runnable接口的任务实例
- 如果是Callable接口,通过executorService.submit()方式提交线程任务
- 通用方法:不论是实现了Runnable或Callable接口的类,均可以通过ExecutorService接口提交任务,如:
ExecutorService executorService = Executors.newFixedThreadPool(10);
executorService.execute(Runnabel r)
executorService.submit(Runnable r)
executorService.submit(Callable<T> c)
3. 通过ExecutorService方法和普通的线程执行方法的区别
- ExecutorService是基于线程池创建的线程任务执行接口类,采用线程任务的定义和执行分离的思路,可以方便地进行线程管理、调度;而普通线程方法,一般创建后就立即执行。
- ExecutorService继承自Excutor接口(这个接口只有一个方法execute(Runnable r)方法),扩展了任务的shutdown(),shutdownNow(),invokeAll()、submit()等方法
- ExecutorService的一个非常常用的实现类便是ThreadPoolTaskExecutor
4. ExecuteService接口中的submit和execute方法区别
- submit有返回值,返回值是Future<T>类型,execute没有返回值
- 查看源码发现,submit其实是通过RunnableFuture<T>对任务进行了包装,最终是调用了execute(Runnable r)方法
public <T> Future<T> submit(Callable<T> task) {
if (task == null) throw new NullPointerException();
RunnableFuture<T> ftask = newTaskFor(task);
execute(ftask);
return ftask;
}
5. Future和FutureTask<T>的区别
Future是一个接口类,接口如下:
- boolean cancel(boolean mayInterruptIfRunning);
- boolean isCancelled();
- boolean isDone();
- V get() throws InterruptedException, ExecutionException;
- V get(long timeout, TimeUnit unit) throws InterruptedException, xecutionException, TimeoutException;
FutureTask实现了RunnableFuture接口,而Runnable继承了Runnable、Future两个接口,它有个两个构造方法
public FutureTask(Callable<V> callable) {
}
public FutureTask(Runnable runnable, V result) {
}
这意味着可以对实现了Callable或者Runnable接口的线程任务类进行包装,普通线程类也可以不通过ExecutorService的submit方法获取返回值,如下所示。
FutureTask<Integer> task = new FutureTask<Integer>(new Sum(subMin,subMax));
new Thread(task).start();
System.out.println(task.get());// 获取返回值
关于FutureTask和Future的描述,其实在Future中已经描述得比较仔细了
/**
A cancellable asynchronous computation. This class provides a
base* implementation of {@link Future}, with methods to start and
cancel* a computation, query to see if the computation is complete,
and* retrieve the result of the computation. The result can only
be* retrieved when the computation has completed; the {@code get}* methods will block if the computation has not yet completed.
Once* the computation has completed, the computation cannot be
restarted* or cancelled (unless the computation is invoked using
{@link #runAndReset}).
大意为:一个可异步取消的计算任务。
这个类提供了Future的基本实现,包括启动或取消一个任务,查询任务是否计算完毕以及返回任务执行结果。
只有当任务结束时才能获取到返回的结果;如果没有执行完毕,get()方法将会阻塞。
一旦任务完成,计算过程不能重启或者取消,除非调用了runAndReset方法。
*/
public class FutureTask<V> implements RunnableFuture<V> {
//……
}
6. DEMO
为充分利用CPU资源进行大数求和, 采用多线程方式进行分解。
package com.whc.test2;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
/**
* @ClassName SumCalculator
* @Description TODO
* @Author Administrator
* @Date 2018/12/16 21:08
* @Version 1.0
*/
public class SumCalculator {
private class Sum implements Callable<Integer>{
private int subMin;
private int subMax;
public Sum(int subMin, int subMax) {
this.subMin = subMin;
this.subMax = subMax;
}
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = subMin; i <= subMax; i++){
sum += 1;
System.out.println(Thread.currentThread().getName()+"-----"+sum);
}
return sum;
}
}
/**
* 多线程求和min~max
* @param min
* @param max
* @param threadSum
* @return
*/
public Integer getSum(int min, int max, int threadSum){
int subMin;
int subMax;
List<FutureTask<Integer>> taskList = new ArrayList<>();
int sumCounts = max - min + 1;
int subCounts = sumCounts/threadSum;
int remainder = subCounts%threadSum;
int mark = min;
for (int i = 0; i < threadSum;i++){
subMin = mark;
if (remainder!=0 && remainder >1){
subMax = subMin + subCounts;
}else{
subMax = mark + subCounts - 1;
}
mark = subMax + 1;
System.out.println(subMin+":"+subMax);
/**
* 定义FutureTask类对任务进行包装,接受返回的结果,也可以通过Executors.newFixedThreadPool获取ExecuteService,
之后通过Future f = ExecuteService.execute(task);获取执行结果
*/
FutureTask<Integer> task = new FutureTask<Integer>(new Sum(subMin,subMax));
taskList.add(task);
new Thread(task).start();
}
int sum = taskListSum(taskList);
return sum;
}
/**
* 遍历结果集,取数
*/
private Integer taskListSum(List<FutureTask<Integer>> taskList) {
int sum = 0;
for (FutureTask<Integer> task: taskList){
try {
// 这是一个阻塞方法,有数才返回
sum += task.get();
}catch (InterruptedException e){
e.printStackTrace();
}catch (ExecutionException e){
e.printStackTrace();
}
}
return sum;
}
public static void main(String[] args){
SumCalculator sumCalculator = new SumCalculator();
int sum = sumCalculator.getSum(1,100,5);
System.out.println(sum);
}
}
网友评论