Java 线程可返回值类:Future

使用多线程统计某文件夹下,所有包含关键字的文件数量,每个文件夹新启一个线程统计,需要返回线程的结果。

package com.learn.corejava.threading;



import java.io.File;

import java.io.FileNotFoundException;

import java.util.ArrayList;

import java.util.List;

import java.util.Scanner;

import java.util.concurrent.Callable;

import java.util.concurrent.ExecutionException;

import java.util.concurrent.Future;

import java.util.concurrent.FutureTask;



public class FutureMain {

    public static void main(String[] args) {

        String path = "E:\\cspp";

        String keyword = "python";



        MatchCounter matchCounter = new MatchCounter(new File(path), keyword);

        FutureTask<Integer> task = new FutureTask(matchCounter);

        new Thread(task).start();

        try {

            int count = task.get();

            System.out.println(count + " matching files.");

        } catch (InterruptedException e) {

            e.printStackTrace();

        } catch (ExecutionException e) {

            e.printStackTrace();

        }

    }

}



class MatchCounter implements Callable<Integer> {



    private File directory;

    private String keyword;



    public MatchCounter(File directory, String keyword) {

        this.directory = directory;

        this.keyword = keyword;

    }



    @Override

    public Integer call() throws Exception {

        int count = 0;



        File[] files = directory.listFiles();

        List<Future<Integer>> futures = new ArrayList<>();

        for (File file : files) {

            if (file.isDirectory()) {

                MatchCounter matchCounter = new MatchCounter(file, keyword);

                FutureTask<Integer> task = new FutureTask<>(matchCounter);

                futures.add(task);

                new Thread(task).start();

            } else {

                if (search(file)) {

                    count++;

                }

            }

        }



        for (Future<Integer> futureTask : futures) {

            count += futureTask.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;

    }

}


 

 

展开阅读全文