多線程涉及的類能夠分爲如下幾類:java
可執行對象:最基本的多線程編程
執行器:簡化多線程編程api
工具類多線程
容器架構
併發控制併發
1、可執行對象:oracle
一、Runnable:異步
執行單位:Thread工具
建立線程的兩種方式(來自於Java API doc):ui
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方法。 . . . }
二、Callable:相對於Runnable,Callable能夠返回結果、拋出checked exception。
package java.util.concurrent; public interface Callable<V> { V call() throws Exception; // 泛型V定義了返回的類型 }
三、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。
2、執行器:
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
待續……
3、容器:
BlockingDeque
待續……
4、併發控制:
Synchronized
CountDownLatch
待續……
5、工具類:
Executors:一些工廠、工具方法
相關文章:
一、高可用架構—併發之痛 Thread,Goroutine,Actor
refer:
一、Java併發性和多線程介紹目錄:http://ifeve.com/java-concurrency-thread-directory/
二、Doug Lea併發編程文章所有譯文:http://ifeve.com/doug-lea/