用阻塞队列来控制线程集

package org.chapter.thread;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;


/**
 * 
 * 该程序主要用阻塞队列来控制线程集 程序在一个目录以及它所有的子目录下搜索所有文件 打印出指定关键字的行
 * 
 */
public class BlockingQueueTest {


public static void main(String[] args) {


Scanner in=new Scanner(System.in);
System.out.print("请输入文件目录地址:");
String directory=in.nextLine();
System.out.print("请输入查询关键字:");
String keyword=in.nextLine();
final int FILE_QUEUE_SIZE=10;

final int SEARCH_THREADS=100;

BlockingQueue<File> queue= new ArrayBlockingQueue<File>(FILE_QUEUE_SIZE);
FileEnumerationTask enumrator=new FileEnumerationTask(queue, new File(directory));
//开起线程
new Thread(enumrator).start();
for (int i = 0; i < SEARCH_THREADS; i++) {
new Thread(new SearchTask(queue, keyword)).start();
}
}


}


class FileEnumerationTask implements Runnable {


private BlockingQueue<File> queue;
private File startingDirectory;
public static File DUMMY = new File("");


@Override
public void run() {


try {
enumerate(startingDirectory);
queue.put(DUMMY);
} catch (InterruptedException e) {


}


}


public FileEnumerationTask(BlockingQueue<File> queue, File startingDirectory) {
this.queue = queue;
this.startingDirectory = startingDirectory;
}


// 递归循环
public void enumerate(File directory) throws InterruptedException {
// 得到该文件目录下的所有文件
File[] files = directory.listFiles();
for (File file : files) {


if (file.isDirectory())
// 此处采用递归
enumerate(file);
else
// 添加元素,如果队列满了,就阻塞
queue.put(file);
}


}


}


class SearchTask implements Runnable {


private BlockingQueue<File> queue;
private String keyword;


@Override
public void run() {
try {
boolean done = false;
while (!done) {
File file = queue.take();
if (file == FileEnumerationTask.DUMMY) {
queue.put(file);
done = true;
} else
serach(file);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}


public SearchTask(BlockingQueue<File> queue, String keyword) {
this.queue = queue;
this.keyword = keyword;
}


public void serach(File file) throws FileNotFoundException {
Scanner in = new Scanner(new FileInputStream(file));
int lineNumber = 0;
while (in.hasNextLine()) {
lineNumber++;
String line = in.nextLine();
if (line.contains(keyword))
System.out.println("文件路径:" + file.getPath() + "-行数:"
+ lineNumber + "-内容:" + line);
}
in.close();


}


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值