java future 返回值_Java 线程可返回值类:Future

该博客展示了如何在Java中使用Future和Callable接口来实现多线程,统计指定文件夹及其子文件夹中包含特定关键字的文件数量。通过创建FutureTask并在新线程中启动,主线程可以等待并获取每个线程的统计结果。
摘要由CSDN通过智能技术生成

使用多线程统计某文件夹下,所有包含关键字的文件数量,每个文件夹新启一个线程统计,需要返回线程的结果。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 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 {

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> futures = new ArrayList<>();

for (File file : files) {

if (file.isDirectory()) {

MatchCounter matchCounter = new MatchCounter(file, keyword);

FutureTask task = new FutureTask<>(matchCounter);

futures.add(task);

new Thread(task).start();

} else {

if (search(file)) {

count++;

}

}

}

for (Future 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;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值