线程_线程池
Posted huangpeideng
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了线程_线程池相关的知识,希望对你有一定的参考价值。
1.认识Executor接口 最顶层接口
package com.hpd.executor; import java.util.concurrent.Executor; public class T01_MyExecutor implements Executor { public static void main(String[] args) { new T01_MyExecutor().execute(()->System.out.println("helllo executor")); } @Override public void execute(Runnable command) { //new Thread(command).start();//开启一个线程去调用 command.run();//直接的方法调用 } }
2.ExecutorService接口 (继承自Executor接口)
除了继承的executor()方法外,还提供了submit(Callable<T> task)方法,submit(Runnable task)
3Executors工具类
4ThreadPool
package com.hpd.executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import javax.swing.plaf.synth.SynthSplitPaneUI; public class T02_ThreadPool { public static void main(String[] args) throws InterruptedException { ExecutorService service = Executors.newFixedThreadPool(5); for(int i=0;i<6;i++) { service.execute(()->{ try { TimeUnit.MICROSECONDS.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()); }); } System.out.println(service); service.shutdown(); System.out.println(service.isTerminated()); System.out.println(service.isShutdown()); System.out.println(service); TimeUnit.MICROSECONDS.sleep(5000); System.out.println(service.isTerminated()); System.out.println(service.isShutdown()); System.out.println(service); } }
[email protected][Running, pool size = 5, active threads = 5, queued tasks = 1, completed tasks = 0]
false
true
[email protected][Shutting down, pool size = 5, active threads = 5, queued tasks = 1, completed tasks = 0]
pool-1-thread-2
pool-1-thread-4
pool-1-thread-1
pool-1-thread-5
pool-1-thread-3
pool-1-thread-2
true
true
[email protected][Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 6]
5FutureTask和Future
package com.hpd.executor; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; public class T03_Future { public static void main(String[] args) throws InterruptedException, ExecutionException { FutureTask<Integer> task = new FutureTask<>(()-> { //用FurureTask包装Callable任务 TimeUnit.MILLISECONDS.sleep(500); //Thread只能传入FutureTask不能传入Callable return 1000; }); new Thread(task).start(); System.out.println(task.get());//阻塞 ExecutorService service = Executors.newFixedThreadPool(5); Future<Integer> f= service.submit(()->{ //submit方法直接传入Callable任务 TimeUnit.MICROSECONDS.sleep(500); return 1; }); System.out.println(f.isDone()); } }
6.------
以上是关于线程_线程池的主要内容,如果未能解决你的问题,请参考以下文章