zoukankan      html  css  js  c++  java
  • 线程池

    使用线程池方式—Callable接口
    Callable接口:与Runnable接口功能相似,用来指定线程的任务。其中的call()方法,用来返回线程任务执行完毕后的结果,call方法可抛出异常。
    ExecutorService:线程池类
    <T> Future<T> submit(Callable<T> task):获取线程池中的某一个线程对象,并执行线程中的call()方法
    Future接口:用来记录线程任务执行完毕后产生的结果。线程池创建与使用
    
    使用线程池中线程对象的步骤:
    创建线程池对象
    创建Callable接口子类对象
    提交Callable接口子类对象
    关闭线程池
    import java.util.concurrent.Callable;
    
    public class MyCallable implements Callable<String>{
        public String call() throws Exception {
            return "abc";
        }
    }
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    
    public class Test1 {
        public static void main(String[] args) throws InterruptedException, ExecutionException {
            //1.先从线程池工厂中获取线程池对象
            ExecutorService es=Executors.newFixedThreadPool(2);
            //2.执行线程任务获取call方法执行后的返回值
            Future<String> str=es.submit(new MyCallable());
            //3.从Future对象中获取返回值
            String s=str.get();
            System.out.println(s);//abc
            //销毁线程池
            es.shutdown();
        }
    }
    线程池练习:返回两个数相加的结果
    import java.util.concurrent.Callable;
    
    public class CallSum implements Callable<Integer>{
        private int num;
        public CallSum(){}
        public CallSum(int num){
            this.num=num;
        }
        public Integer call() throws Exception {
            int sum=0;
            for(int i=1;i<num;i++){
                sum+=i;
            }
            return sum;
        }
    }
    
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    
    public class Demo03 {
        //用线程实现计算
        //由两个线程分别计算1-100的和  1-200的和
        public static void main(String[] args) throws InterruptedException, ExecutionException {
            ExecutorService es=Executors.newFixedThreadPool(2);
            Future<Integer> f=es.submit(new CallSum(100));
            System.out.println(f.get());
            Future<Integer> f1=es.submit(new CallSum(200));
            System.out.println(f1.get());
            es.shutdown();
        }
    }
     
  • 相关阅读:
    Asp.net 通过Repeater循环添加对应的一组控件
    JS将number数值转化成为货币格式
    Asp.net 在 Postback 之后 执行 javascript 方法
    Asp.net 通过Repeater嵌套Repeater循环添加对应的一组控件
    向SharePoint 2010中添加Permission Level,Group,以及相应的User
    Asp.net 前后台操作cookie 实现数据的循环下载
    JS 将 string 转换成为 number
    C# Dictionary通过value获取对应的key值
    手机相机下的世界
    自定义Data Service Providers — (3)IServiceProvider和DataSources 服务提供者和数据源
  • 原文地址:https://www.cnblogs.com/zhaotao11/p/10250441.html
Copyright © 2011-2022 走看看