一、任務java
串行地執行任務:併發性能低併發
現式地爲任務建立線程來執行任務:無限制的建立線程框架
無限制的建立線程的不足: 線程生命週期開銷高、資源消耗、穩定性。jvm
二、Executor框架:函數
Executor 接口 Executors 類 ExecutorService性能
public interface Executor { void execute(Runnable command); }
public interface ExecutorService extends Executor { void shutdown(); //緩慢關閉:不接受新的任務,等待未開始和執行中的任務完成以後關閉 List<Runnable> shutdownNow(); //當即關閉 boolean isShutdown();//是否關閉 boolean isTerminated(); //判斷全部提交的任務是否完成(保證以前調用過shutdown方法) //Callable 的 call() 方法能夠返回壹個結果。方法 Runnable.run() 則不能返回結果。 <T> Future<T> submit(Callable<T> task); // Future 對象能夠用於判斷 Runnable 是否結束執行 Future<?> submit(Runnable task); }
public class Executors { // 來一個任務建立一個線程,達到線程池大小以後不會建立新的線程 public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); } public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); } public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); } // 和Timer 相比,timer是基於絕對時間而 ScheduledExecutorService 是基於相對時間。 public static ScheduledExecutorService newSingleThreadScheduledExecutor() { return new DelegatedScheduledExecutorService (new ScheduledThreadPoolExecutor(1)); } public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) { return new ScheduledThreadPoolExecutor(corePoolSize); } private Executors() {} ...... }
三、線程狀態this
jvm只有在全部(非守護)線程所有終止時纔會退出。線程
四、code
Future就是對於具體的Runnable或者Callable任務的執行結果進行對象
取消、查詢是否完成、獲取結果、設置結果操做
// Future 接口 public interface Future<V> { boolean cancel(boolean mayInterruptIfRunning); boolean isCancelled(); boolean isDone(); V get() throws InterruptedException, ExecutionException; V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; }
// FutureTask 類 是jdk中 Future 接口的惟一實現類 public class FutureTask<V> implements RunnableFuture<V> { //構造函數1 public FutureTask(Callable<V> callable) { if (callable == null) throw new NullPointerException(); this.callable = callable; this.state = NEW; // ensure visibility of callable } //構造函數2 public FutureTask(Runnable runnable, V result) { this.callable = Executors.callable(runnable, result); this.state = NEW; // ensure visibility of callable } } // RunnableFuture 接口 public interface RunnableFuture<V> extends Runnable, Future<V> { void run(); }
Callable 產生結果,Future拿到結果。
FutureTask實現了兩個接口,Runnable和Future,因此它既能夠做爲Runnable被線程執行,又能夠做爲Future獲得Callable的返回值。
那麼這個組合FutureTask的使用有什麼好處呢?假設有一個很耗時的返回值須要計算,而且這個返回值不是馬上須要的話,那麼就可使用這個組合,用另外一個線程去計算返回值,而當前線程在使用這個返回值以前能夠作其它的操做,等到須要這個返回值時,再經過Future獲得