线程池的概念和使用

线程池

线程池的相关概念

  • 背景:经常创建和销毁、使用量特别大的资源,比如并发情况下的线程,对性能影响很大。
  • 思路:提取创建好多个线程,放入线程池中,使用时直接获取,使用完放回线程池中。可以避免频繁的创建销毁、实现重复利用。类似生活中的公共交通工具
  • 好处:
    • 提高响应速度(减少了创建新线程的时间)
    • 降低资源消耗(重复利用线程池中线程,不需要每次都创建)
    • 便于线程管理
      • corePoolSize: 核心池大小
      • maximumPoolSize: 最大线程数
      • keepActiveTime: 线程没有任务时最多保持多长时间后会终止

线程池的使用

  • JDK 5.0起提供了线程池相关API:ExecutorService和Executors

  • ExecutorService: 真正的线程池接口。常见子类ThreadPoolExecutor

    • void execute(Runnable command):执行任务/命令,没有返回值,一般用来执行Runnable

      代码实现:

      import java.util.concurrent.ExecutorService;
      import java.util.concurrent.Executors;
      
      //测试线程池
      public class TestPool {
      
          public static void main(String[] args) {
              //1.创建服务,创建线程池
              //newFixedThreadPool 参数为:线程池大小
              ExecutorService service = Executors.newFixedThreadPool(10);
      
              //执行
              service.execute(new MyThread());
              service.execute(new MyThread());
              service.execute(new MyThread());
              service.execute(new MyThread());
              
              //关闭链接
              service.shutdown();
          }
      }
      
      class MyThread implements Runnable{
      
          @Override
          public void run() {
              System.out.println(Thread.currentThread().getName());
          }
      }
      
    • Future submit(Callable task): 执行任务,有返回值,一般用来执行Callable

      代码实现:

      import org.apache.commons.io.FileUtils;
      
      import java.io.File;
      import java.io.IOException;
      import java.net.URL;
      import java.util.concurrent.*;
      
      //线程创建方式三:实现Callable接口
      /*
          callable的好处:
          1.可以自定义返回值
          2.可以抛出异常
       */
      public class TestCallable implements Callable<Boolean> {
          private String url;
          private String name;
      
          public TestCallable(String url, String name){
              this.url = url;
              this.name = name;
          }
      
          //下载图片线程的执行体
          @Override
          public Boolean call() {
              WebDownLoader webDownLoader = new WebDownLoader();
              webDownLoader.downloader(url, name);
              System.out.println("下载了文件名为:" + name);
              return true;
          }
      
          public static void main(String[] args) throws ExecutionException, InterruptedException {
              TestCallable t1 = new TestCallable("https://img2.baidu.com/it/u=2379421903,2766120725&fm=26&fmt=auto&gp=0.jpg", "1.jpg");
              TestCallable t2 = new TestCallable("https://img0.baidu.com/it/u=2580887492,2953392680&fm=26&fmt=auto&gp=0.jpg", "2.jpg");
              TestCallable t3 = new TestCallable("https://img2.baidu.com/it/u=3562631285,4033075858&fm=26&fmt=auto&gp=0.jpg", "3.jpg");
      
              //创建执行服务:
              ExecutorService ser = Executors.newFixedThreadPool(3);
      
              //提交执行
              Future<Boolean> r1 = ser.submit(t1);
              Future<Boolean> r2 = ser.submit(t2);
              Future<Boolean> r3 = ser.submit(t3);
      
              //获取结果
              boolean rs1 = r1.get();
              boolean rs2 = r2.get();
              boolean rs3 = r3.get();
      
              System.out.println(rs1);
              System.out.println(rs2);
              System.out.println(rs3);
      
              //关闭服务
              ser.shutdownNow();
          }
      }
      
      //下载器
      class WebDownLoader{
          //下载方法
          public void downloader(String url, String name){
              try {
                  FileUtils.copyURLToFile(new URL(url), new File(name));
              } catch (IOException e) {
                  e.printStackTrace();
                  System.out.println("IO异常,downloader方法出现问题");
              }
          }
      }
      
    • void shutdown(): 关闭连接池

  • Executors: 工具类、线程池的工厂类,用于创建并返回不同类型的线程池

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值