Java 多线程,线程池,

Wesley13
• 阅读 521

1. 创建线程池的方法之三:

//对于每个任务,如果有空闲的线程可用,立即让他执行任务,
    //没有空闲的线程则创建一个线程。
    ExecutorService pool = Executors.newCachedThreadPool();
    //固定大小的线程池,任务数 > 空闲线程数,得不到服务的任务置于队列
    ExecutorService pool = Executors.newFixedThreadPool;
    //退化的大小为1的线程池,由一个线程逐个执行提交的任务。
    ExecutorService pool = Executors.newSingleThreadPool();

2. 把任务交给线程池:

//返回的对象可以调用isDone(),cancel(),isCancelled
    Future<?> submit(Runnable task);
    //get() 返回指定的result对象
    Future<T> submit(Runnable task,T result);
    //返回的对象将在计算结果准备好的时候得到它。
    Future<T> submit(Callable<T> task);

3.用完一个线程池的时候,调用shutdown() 启动线程池的关闭序列。被关闭的执行器不再接受新的任务,当任务都结束后,线程池中的线程死亡。

4. 案例:给定一个目录,查找目录中文本文档内容包含指定关键字的文档的数量。

  条件:目录、关键字

  4.1 任务类(线程类)

/** 线程任务:计算目录中所有包含给定关键字的文件的数量。*/
   class MatchCounter implements Callable<Integer>
   {
      private File directory;
      private String keyword;
      private ExecutorService pool;
      private int count;

      /**
       * Constructs a MatchCounter.
       * @param directory 给定的目录
       * @param keyword 关键字
       * @param pool 用来执行任务的线程池
       */
      public MatchCounter(File directory, String keyword, ExecutorService pool)
      {
         this.directory = directory;
         this.keyword = keyword;
         this.pool = pool;
      }

      @Override
      public Integer call()
      {
         count = 0;
         try
         {
            File[] files = directory.listFiles();
            //线程执行结果集合
            List<Future<Integer>> results = new ArrayList<>();

            for (File file : files)
               //遍历给定目录中的所有文件
               //如果是文件夹
               if (file.isDirectory())
               {
                  //递归
                  MatchCounter counter = new MatchCounter(file, keyword, pool);
                  Future<Integer> result = pool.submit(counter);
                  results.add(result);
               }
               //如果是文件,则调用search()方法 看是否包含关键字。
               else
               {
                  if (search(file)) count++;
               }

            for (Future<Integer> result : results)
               try
               {
                  int a = result.get();
                  count += result.get();
               }
               catch (ExecutionException e)
               {
                  e.printStackTrace();
               }
         }
         catch (InterruptedException e)
         {
         }
         return count;
      }

      /**
       * Searches a file for a given keyword.
       * @param file the file to search
       * @return true if the keyword is contained in the file
       */
      public boolean search(File file)
      {
         try
         {
            try (Scanner in = new Scanner(file, "UTF-8"))
            {
               boolean found = false;
               while (!found && in.hasNextLine())
               {
                  String line = in.nextLine();
                  if (line.contains(keyword)) found = true;
               }
               return found;
            }
         }
         catch (IOException e)
         {
            return false;
         }
      }
   }

  4.2 主程序

public class ThreadPoolTest
   {
      public static void main(String[] args) throws Exception
      {
         try (Scanner in = new Scanner(System.in))
         {
            System.out.print("请输入要查找的目录:");
            String directory = in.nextLine();
            System.out.print("请输入要查找的关键字:");
            String keyword = in.nextLine();
      
            ExecutorService pool = Executors.newCachedThreadPool();
      
            MatchCounter counter = new MatchCounter(new File(directory), keyword, pool);
            Future<Integer> result = pool.submit(counter);
      
            try
            {
               System.out.println(result.get() + " 匹配的文件");
            }
            catch (ExecutionException e)
            {
               e.printStackTrace();
            }
            catch (InterruptedException e)
            {
            }
            pool.shutdown();
      
            int largestPoolSize = ((ThreadPoolExecutor) pool).getLargestPoolSize();
            System.out.println("线程池最大数量 =" + largestPoolSize);
         }
      }
   }

  4.3 运行结果:

  Java 多线程,线程池,

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Wesley13 Wesley13
2年前
java 面试知识点笔记(十三)多线程与并发
java线程池,利用Exceutors创建不同的线程池满足不同场景需求:1.newSingleThreadExecutor() 创建一个单线程的线程池。这个线程池只有一个线程在工作,也就是相当于单线程串行执行所有任务。如果这个唯一的线程因为异常结束,那么会有一个新的线程来替代它。此线程池保证所有任务的执行顺序按照任务的提交顺序执行。2.
Wesley13 Wesley13
2年前
JAVA多线程学习
Java通过Excutors提供四种线程池:newCachedThreadPool        创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。newFixedThreadPool        创建一个定长线程,可控制线程最大并发数
Stella981 Stella981
2年前
Jetty调优文档
1.      线程池线程池线程资源大小确定了服务器的服务能力默认大小不一定能满足生产环境线程分配方式决定了服务器的资源利用效率固定线程数处理多任务,代表:JDK的ThreadPoolExecutor       以最大的线程数为限处理多任务,代表:jetty自带的QueuedThreadPoolje
Wesley13 Wesley13
2年前
Java通过Executors提供四种线程池
Java通过Executors提供四种线程池,分别为:newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。newFixedThreadPool创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。newScheduledThreadPool创建
Stella981 Stella981
2年前
ExecutorService 线程池 (转发)
1.ExecutorServicejava.util.concurrent.ExecutorService接口。用来设置线程池并执行多线程任务。它有以下几个方法。Future<?java.util.concurrent.ExecutorService.submit(Runnabletask)提交任务并执行,返回代表这个任务的future
Wesley13 Wesley13
2年前
Java基础教程——线程池
启动新线程,需要和操作系统进行交互,成本比较高。使用线程池可以提高性能——线程池会提前创建大量的空闲线程,随时待命执行线程任务。在执行完了一个任务之后,线程会回到空闲状态,等待执行下一个任务。(这个任务,就是Runnable的run()方法,或Callable的call()方法)。Java5之前需要手动实现线程池,Java5之
Stella981 Stella981
2年前
Noark入门之线程模型
0x00单线程多进程单线程与单进程多线程的目的都是想尽可能的利用CPU,减少CPU的空闲时间,特别是多核环境,今天咱不做深度解读,跳过...0x01线程池锁最早的一部分游戏服务器是采用线程池的方式来处理玩家的业务请求,以达最大限度的利用多核优势来提高处理业务能力。但线程池同时也带来了并发问题,为了解决同一玩家多个业务请求不被
Wesley13 Wesley13
2年前
Java 基础知识(七)
1.创建线程池1)newCacheThreadPool 创建一个可缓存的线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程 2)newFixedThreadPool  创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待 3)newScheduledThreadPool  创建一个定长线程池,支持
Wesley13 Wesley13
2年前
Java多线程之线程池
 newFixedThreadPool:固定线程池,核心线程数和最大线程数固定相等,而空闲存活时间为0毫秒,说明此参数也无意义,工作队列为最大为Integer.MAX\_VALUE大小的阻塞队列。当执行任务时,如果线程都很忙,就会丢到工作队列等有空闲线程时再执行,队列满就执行默认的拒绝策略 newCachedThreadPool:带缓冲