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;
    }
}

 

 

原文地址: https://www.zhblog.net/go/java/tutorial/java8-future-task?t=590

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章