Java多线程查找指定文件夹下包含指定关键字的文件数量(线程池版)

该博客演示了如何使用Java多线程和线程池查找指定文件夹(F:\C++ Project)下包含特定关键字(namespace)的文件数量。通过创建`ThreadPoolTest`类,利用`ExecutorService`和`Callable`接口实现递归搜索,最后输出匹配的文件数量及线程池的最大大小。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

public class ThreadPoolTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		File directory = new File("F:\\C++ Project");
		String keyWords = "namespace";
		ExecutorService pool = Executors.newCachedThreadPool();
		Future<Integer> future = pool.submit(new PoolMatchCounter(directory, keyWords, pool));
		try {
			System.out.println(future.get() + " files match");
		} catch (InterruptedException | ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		pool.shutdown();
		ThreadPoolExecutor executor = (ThreadPoolExecutor)pool;
		System.out.println("Largest Pool Size: " + executor.getLargestPoolSize());
	}

}

class PoolMatchCounter implements Callable<Integer>{
	
	private File directory;
	private String keyWords;
	private ExecutorService pool;
	
	public PoolMatchCounter(File directory, String keyWords, ExecutorService pool) {
		super();
		this.directory = directory;
		this.keyWords = keyWords;
		this.pool = pool;
	}

	@Override
	public Integer call() throws Exception {
		// TODO Auto-generated method stub
		File[] files = directory.listFiles();
		List<Future<Integer>> result = new ArrayList<>();
		int count = 0;
		for(File f : files){
			if(f.isDirectory()){
				Future<Integer> future = pool.submit(new PoolMatchCounter(f, keyWords, pool));
				result.add(future);
			}else{
				if(search(f)) ++count;
			}
		}
		
		for(Future<Integer> f : result){
			count += f.get();
		}
		return count;
	}
	
	
	public boolean search(File f) throws FileNotFoundException{
		try(Scanner in = new Scanner(f)){
			boolean found = false;
			while(!found&in.hasNextLine()){
				String line = in.nextLine();
				if(line.contains(keyWords)){
					found = true;
				}
			}
			return found;
		}
	}
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值