• 线程池, Callable<V>接口


    线程池:

    概念:线程池,其实就是一个容纳多个线程的容器,其中的线程可以反复使用,省去了频繁创建线程对象的操作,无需反复创建线程而消耗过多资源。

    Executors:线程池创建工厂类

    ExecutorService:线程池类

    ExecutorService er=Executors.newFixedThreadPool(int);返回线程池对象

    submit()获取线程池中的某一个线程对象,并执行线程中的call()方法

    shutdown();释放资源

    例:

    //获取线程池对象

    ExecutorService er=Executors.newFixedThreadPool(2);

    //创建线程任务对象

    MyRunnable mr=new MyRunnable();//自定义类

    //开启线程

    er.submit(mr);

    //释放

    er.shutdown();

    Callable<V>接口

     

    与Runnable接口功能相似,用来指定线程的任务。其中的call()方法,用来返回线程任务执行完毕后的结果,call方法可抛出异常。

    Future<V> 用来接收执行结束后的返回结果

    //创建线程任务

    MyCallable mc=new MyCallable();//自定义类,实现Callavle接口,重写call方法 ,有返回值

    //创建线程池工厂

    ExecutorService es=Executors.newFixedThreadPool(2);

    //执行线程任务

    Future<Integer> f=es.submit(mc);

    //获取返回值

    System.out.println(f.get());//.get()方法获取返回值

    es.shutdown();

  • 相关阅读:
    Java8 lambda表达式语法 1
    Spring WebMVC 4.1返回json时 406(Not Acceptable)
    上传 第三方jar包 nexus
    Nexus 使用配置
    Nexus 安装 使用说明
    mysql 常用命令
    JedisPoolConfig配置
    tomcat 管理端 安全措施
    Java ReentrantLock和synchronized两种锁定机制的对比
    spring 在web容器启动时执行初始化方法
  • 原文地址:https://www.cnblogs.com/hhthtt/p/10632622.html
Copyright © 2020-2023  润新知