02 多线程
1. Callable的实现和接收
- public class CallDemo implements Callable<String> {
-     @Override
-     public String call() throws Exception {
-         Thread.sleep(2000);
-         return "线程回调方法的返回值";
-     }
- }
- public class ThreadTest {
-     public static void main(String[] args) {
-         /*使用call回调方法有两种方式
-         * 1.用线程接收
-         * 2.用线程池接收*/
-         //1.用线程接收
-         CallDemo call = new CallDemo(); //1.创建call对象实例
-         /*
-         *FutureTask是一个类,该类提供了一个Future的基本实现,具有启动和取消计算的方法,查询计算是否完整,并检索计算结果
-         * 结果只能在计算完成后才能检索;如果计算尚未完成,则get方法将其阻止,
-         * 一旦计算完成,则无法重新启动或者取消计算(除非使用runAndReset()调用计算)
-         * 该接口实现的接口:Runnable,Future<V>,RunnableFuture<V> */
-         FutureTask<String> ft = new FutureTask<>(call);//2.创建FutureTask
-         Thread t1 = new Thread(ft);//3.创建线程
-         t1.start();//4.使用线程
-         String str = "";//5.创建变量接收
-         try {
-             str = ft.get();
-         } catch (InterruptedException |ExecutionException e) {
-             e.printStackTrace();
-         }
-         System.out.println(str);
-         //2.线程池
-         ExecutorService es = Executors.newFixedThreadPool(10);
-         Future<String> ft2 = es.submit(call);
-         String str2 = "";
-         try {
-             str2 = ft2.get();
-         } catch (InterruptedException |ExecutionException e) {
-             e.printStackTrace();
-         }
-         System.out.println(str2);
-         es.shutdown();//销毁线程池
-     }
- }
2.newFixedThreadPool的静态方法返回值详情
- public static ExecutorService newFixedThreadPool(int nThreads) {
-         return new ThreadPoolExecutor(nThreads, nThreads,
-                                       0L, TimeUnit.MILLISECONDS,
-                                       new LinkedBlockingQueue<Runnable>());
-     }
- public class Test {
-   public static void main(String[] args) {
-     ExecutorService es = Executors.newFixedThreadPool(10);
-     /*ThreadPoolExecutor(
-       (int corePoolSize => 线程池数量,
-       int maximumPoolSize=> 线程池最大数量,
-        long keepAliveTime=> 就是如果还有没有运行的空闲线程,那么空闲的线程就不能一直开着,所以就设置了一个存活时间,
-        TimeUnit unit=> 时间单位:纳秒,
-        BlockingQueue<Runnable> workQueue => 中文称其为工作队列,是一个用于创建内核线程的接口,
-        通过它创建的内核线程来执行内核其他模块排列到队列里的工作,创建的内核线程被称为工作者线程。
-        ))
-     */
-   }
- }