线程池

  • 构建一个新的线程是有一定代价的,因为涉及与操作系统的交互。如果程序中创建了大量的生命期很短的线程,将Runnable对象交给线程池。一个线程池中包含许多准备运行的空闲线程。将Runnable对象交给线程池,就会有一个线程调用run方法,当run方法退出时,线程不会死亡,而是在池中准备为下一个请求提供服务。
  • 另一个使用线程池的理由是减少并发线程的数目。创建大量线程会大大降低性能,甚至使虚拟机崩溃。如果有一个会创建许多线程的算法,应该使用一个线程数固定的线程池以限制并发线程的总数。
  • 执行器(Executor)类有许多静态工厂方法用来构建线程池。
    执行者工厂方法
  • newCachedThreadPool方法构建一个线程池,对于每个任务,如果有空闲线程可用,立即让它执行任务,如果没有可用的线程,则创建一个新线程。
  • newFixedThreadPool方法构建一个具有固定大小的线程池。如果提交的任务数多于空闲的线程数,那么把得不到服务的任务放置到队列中。当其他任务完成以后再运行它们。
  • newSingleThreadExecutor是一个退化了的大小为1的线程池:由一个线程执行提交的任务,一个接着一个。
  • 这3个方法返回实现了ExecutorService接口的ThreadPoolExecutor类的对象。
  • 可用下面方法将一个Runnable对象或Callable对象提交给ExecutorService:
Future<?> submit(Runnable task);
Future<T> submit(Runnable task, T result);
Future<T> submit(Callable<T> task);
  • 第一个submit方法返回一个奇怪样子的Future<?>。可以使用这样一个对象来调用isDonecancelisCancelled。但是,get方法在完成的时候只是简单地返回null
  • 第二个版本的submit也提交一个Runnable,并且Futureget方法在完成的时候返回指定的result对象。
  • 第三个版本的submit提交一个Callable,并且返回的Future对象将在计算结果准备好的时候得到它。
  • 当用完一个线程池的时候,调用shutdown。该方法启动该池的关闭序列。被关闭的执行器不再接受新的任务。当所有任务都完成后,线程池中的线程死亡。另一种方法是调用shutdownNow。该池取消尚未开始的所有任务并试图中断正在运行的线程。
  • 使用线程池的步骤,如下
调用Executors类中的静态方法newCachedThreadPool或newFixedThreadPool
调用submit提交Runnable或Callable对象
如果想要取消一个任务,或如果提交Callable对象,那就要保存好返回的Future对象
当不再提交任何任务时,调用shutdown。
Runnable r =()->{
        System.out.println("当前时刻"+new Date()); 
        };
        //无须手动开启线程
        //Thread thread = new Thread(r);
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(50);
        Future<?> future = cachedThreadPool.submit(r);
        //future.cancel(false);
        cachedThreadPool.shutdownNow();
public class ThreadPoolTest {
    public static void main(String[] args) {
        try(Scanner in = new Scanner(System.in)){
            System.out.println("Enter base directory (e.g /usr/local/jdk5.0/src):");
            String directory = in.nextLine();
            System.out.println("Enter keyword (e.g volatile):");
            String keyword = in.nextLine();

            //调用Executors类中的静态方法newCachedThreadPool
            ExecutorService pool = Executors.newCachedThreadPool();

            MatchCounter counter = new MatchCounter(new File(directory),keyword,pool);

            //调用submit提交Callable对象
            Future<Integer> result = pool.submit(counter);

            try {
                System.out.println(result.get() +" matching files.");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }finally {
                //当不再提交任何任务时,调用shutdown。
                pool.shutdown();
            }
            int largestPoolSize = ((ThreadPoolExecutor)pool).getLargestPoolSize();
            System.out.println("largest pool size = " + largestPoolSize);
        }
    }
    static class MatchCounter implements Callable<Integer>{
        private File directory;
        private String keyword;
        private ExecutorService pool;
        private int count = 0;

        public MatchCounter(File directory, String keyword, ExecutorService pool) {
            this.directory = directory;
            this.keyword = keyword;
            this.pool = pool;
        }

        @Override
        public Integer call() throws Exception {
            count = 0;

            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);
                }else {
                    if(search(file)) count++;
                }
            }
            for(Future<Integer> result:results){
                count += result.get();
            }
            return count;
        }
        public boolean search(File file){
            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 (FileNotFoundException e) {
                e.printStackTrace();
            }
            return false;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值