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 的阻塞、轮询。
参考: