Thread、Runnable 建立多線程多線程
new Thread(new Runnable() { public void run() { System.out.println("hello"); } }).start();
FutureTask 獲取線程執行結果框架
FutureTask futureTask = new FutureTask(new Callable() { public Object call() throws Exception { return "hello"; } }); new Thread(futureTask).start(); String res = (String)futureTask.get();// block
ExecutorService 更簡便的獲取線程執行結果方式異步
ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<String> future = executorService.submit(new Callable<String>() { public String call() throws Exception { return "hello"; } }); String res = future.get();
ThreadPoolExecutor 線程池工具
多線程缺點:頻繁建立、銷燬線程ui
線程池:封裝任務,加入線程池執行,線程可重複使用。.net
// 多線程 for (int i=0; i<5; i++) { new Thread(new Runnable() { public void run() { System.out.println("hello "); } }).start(); }
// 自定義線程池 public static ThreadPoolExecutor getThreadPool(int queueSize, int multi) { int cpuNum = Runtime.getRuntime().availableProcessors(); queueSize = queueSize == 0 ? cpuNum*10 : queueSize; ArrayBlockingQueue jobs = new ArrayBlockingQueue(queueSize); ThreadPoolExecutor executor = new ThreadPoolExecutor(cpuNum*multi, cpuNum*5, 5, TimeUnit.SECONDS, jobs); executor.allowCoreThreadTimeOut(true);// will shutdown if no task arrive within the keep-alive time return executor; }
jdk 自帶的 Executors 類封裝了一些經常使用線程池,方便快速建立。線程
Executor框架包括:線程池,Executor,Executors,ExecutorService,CompletionService,Future,Callable等。code
ps:blog
多線程和 CountDownLatch 使用。圖片
jdk 自帶工具 jconsole 可查看 vm 狀態。
int taskNum = 20; final CountDownLatch latch = new CountDownLatch(taskNum);// 初始化任務總數 for (int i=0; i<taskNum; i++) { final int tmp = i; new Thread(new Runnable() { public void run() { System.out.println("hello "+tmp); latch.countDown();// 完成一個任務,計數器減一 } }).start(); } try { latch.await();// 阻塞到全部任務完成 System.out.println("finish..."); } catch (InterruptedException e) { e.printStackTrace(); }
jdk 8 中 CompletableFuture 能夠實現異步回調,而不是 Future 的阻塞、輪詢。
參考: