多线程涉及的类可以分为以下几类:
可执行对象:最基本的多线程
执行器:简化多线程编程
工具类
容器
并发控制
一、可执行对象:
1、Runnable:
执行单位:Thread
创建线程的两种方式(来自于Java API doc):
class PrimeThread extends Thread { long minPrime; PrimeThread(long minPrime) { this.minPrime = minPrime; } public void run() { // compute primes larger than minPrime . . . } } PrimeThread p = new PrimeThread(143); p.start();
class PrimeRun implements Runnable { long minPrime; PrimeRun(long minPrime) { this.minPrime = minPrime; } public void run() { // compute primes larger than minPrime . . . } } PrimeRun p = new PrimeRun(143); new Thread(p).start();
Runnable接口非常简单:
package java.lang; public interface Runnable { public abstract void run(); }
而Thread类则很复杂……
package java.lang; public class Thread implements Runnable { //因为Thread继承了Runnable,所以继承自Thread的类要实现run方法。 . . . }
2、Callable:相对于Runnable,Callable可以返回结果、抛出checked exception。
package java.util.concurrent; public interface Callable<V> { V call() throws Exception; // 泛型V定义了返回的类型 }
3、Future:相对于Callable,是一个异步执行的操作
package java.util.concurrent; public interface Future<V> { boolean cancel(boolean mayInterruptIfRunning); boolean isCancelled(); V get() throws InterruptedException, ExecutionException; V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; }
FutureTask: 以上均接口,这是第一个类
实现了Runnable、Future,因此可以把FutrueTask丢给Executor。
二、执行器:
Executor:管理任务
package java.util.concurrent; public interface Executor { void execute(Runnable command); // 可以执行Runnable的执行器,只返回void。 }
ExecutorService:可以执行Runnable和Callable,可以返回Future,异步。可以被shut down, 即拒绝新的task.
直接实现类:ThreadPoolExecutor
间接实现类:ScheduledThreadPoolExecutor。和 ThreadPoolExecutor 相比,ScheduledThreadPoolExecutor 它可另行安排在给定的延迟后运行命令,或者定期执行命令。
package java.util.concurrent; public interface ExecutorService extends Executor { void shutdown(); List<Runnable> shutdownNow(); boolean isShutdown(); boolean isTerminated(); boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException; <T> Future<T> submit(Callable<T> task); <T> Future<T> submit(Runnable task, T result); // 此处是如何返回Result的?? Future<?> submit(Runnable task); <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException; <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException; <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException; <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; }
CompletionService
待续……
三、容器:
BlockingDeque
待续……
四、并发控制:
Synchronized
CountDownLatch
待续……
五、工具类:
Executors:一些工厂、工具方法
refer:
1、Java并发性和多线程介绍目录:http://ifeve.com/java-concurrency-thread-directory/