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);
        }
    }
  • 相关阅读:
    序列化限流排序
    linux常用命令
    Django路径问题
    asp.net 后台 修改 javascript 变量
    支持 IE8 IE11 和 FF, Chrome 浏览器的圆角
    Asp.net Response.Redirect with post data
    gridview 字段没有绑定由于column visible= false
    聪明的小技巧
    GridView
    各种集合
  • 原文地址:https://www.cnblogs.com/geekdc/p/10216409.html
Copyright © 2011-2022 走看看