一.并发包的基本概念
线程Thread即表示要执行的任务,又表示执行的机制。
Java并发包提供了一套“异步任务执行服务”机制,将“任务的提交”和“任务的执行”相分离。
二.并发包的基础类
任务执行服务涉及到的基本接口:
Runnable和Callable:表示要执行的异步任务
Executor和ExecutorService:表示执行服务
Future:表示异步任务的结果
Runnable和Callable都是接口,Runnable没有返回结果,而Callable有,Runnable不会抛出异常,而Callable会。
三.并发包的简单应用
1.Executor
Executor表示最简单的执行服务
public interface Executor {
void execute(Runnable command);
}
可以执行一个Runnable,没有返回结果。接口没有限定任务如何执行,可能是创建一个新线程,可能是复用线程池中的某个线程
2. ExecutorService
public interface ExecutorService extends Executor {
// 对于Callable,任务最终有个返回值
<T> Future<T> submit(Callable<T> task);
// Runnable是没有返回值的,但可以提供一个结果,在异步任务结束时返回
<T> Future<T> submit(Runnable task, T result);
// 最终返回null
Future<?> submit(Runnable task);
}
3.Future:
public interface Future<V> {
// 用于取消异步任务,如果任务已完成、或已取消、或由于某种原因不能取消,返回false,否则返回true
// 如果任务还未开始,则不再运行。如果任务已经在运行,则不一定能取消
// 参数mayInterruptIfRunning表示,如果任务正在执行,是否调用interrupt方法中断线程,如果为false就不会,如果为true就会尝试中断线程,中断不一定能取消线程
boolean cancel(boolean mayInterruptIfRunning);
// 表示任务是否被取消,只要cancel方法返回了true,随后的isCancelled方法都会返回true,即使执行任务的线程还未真正结束
boolean isCancelled();
// 表示任务是否结算,不管什么原因导致结束的
boolean isDone();
// 返回执行结果,如果任务是Runnable且没有提供结果,返回null
// 任务被取消了,会抛出CancellationException
V get() throws InterruptedException, ExecutionException;
V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;
}
四.简单的使用
public class Test {
static class Task implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int sleepSeconds = new Random().nextInt(1000);
Thread.sleep(sleepSeconds);
return sleepSeconds;
}
} public static void main(String[] args) throws InterruptedException {
// 创建一个任务执行服务
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(new Task());
Thread.sleep(100);
try {
System.out.println(future.get());
} catch (ExecutionException e) {
e.printStackTrace();
}
// 关闭任务执行服务
executor.shutdown();
}
}