zoukankan      html  css  js  c++  java
  • 创建线程的第三种方式以及简单使用

    一、Callable接口

      与继承Thread和实现Runnable接口方式创建线程相比,有以下两点不同:

    • 可以有返回值,并且能够获取返回值
    • call()方法允许抛出异常

    二、简单使用

    package com.duchong.thread.callable;
    
    import java.util.concurrent.Callable;
    import java.util.concurrent.FutureTask;
    
    /**
     * @author DUCHONG
     * @since 2019-01-03 11:23
     **/
    public class CallableMain {
    
    
        public static void main(String[] args)throws Exception{
    
            FutureTask<Integer> futureTask=new FutureTask<Integer>(new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    //业务逻辑
                    Integer sum=0;
                    for (int i=1;i<=100;i++){
                        sum+=i;
                    }
                    return sum;
                }
            });
    
            new Thread(futureTask).start();
    
            Integer callResult=futureTask.get();
    
            System.out.println(callResult);
        }
    }
    FutureTask可以看做Runnable和Future的实现类,所以可以作为Thread类的入参。

    三、配合线程池的简单使用

    package com.duchong.thread.callable;
    
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    
    /**
     * 有返回值的Runnable
     *
     * @author DUCHONG
     * @since 2018-07-19 14:15
     **/
    public class CallThread {
    
    
        public static void main(String[] args) throws Exception
        {
            ExecutorService es = Executors.newCachedThreadPool();
    
            Future<String> f = es.submit(new Callable<String>() {
                @Override
                public String call() throws Exception {
                    return "hello callable";
                }
            });
    
            es.shutdown();
            //获取返回值
            String str = f.get();
    
            System.out.println(str);
        }
    }
  • 相关阅读:
    1143 Lowest Common Ancestor (30)
    PAT 1135 Is It A Red-Black Tree
    PAT 1119 Pre- and Post-order Traversals
    1102 Invert a Binary Tree(25 分)
    PAT总结
    c++ getline的用法
    PAT 1049 Counting Ones (30)
    PAT 1022 Digital Library (30)
    java jar包
    NIO的理解
  • 原文地址:https://www.cnblogs.com/geekdc/p/10216409.html
Copyright © 2011-2022 走看看