JAVA阻塞队列(BlockingQueue)实践

一个指定目录下包含某个关键字的文件,输出文件路径及行号。

 

同时启动两组线程,一个向队列中添加文件,一个从队列中取文件,并在文件中查找关键字。

 

 

package com.test.current;

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

public class BlockingQueueTest {
	public static void main(String[] args) {
		//指定目录和关键字
		String directory = "C:\\Program Files\\Java\\jdk1.6.0_29";
		String keyword = "volatile";
		final int FILE_QUEUE_SIZE = 10;//队列长度
		final int SEARCH_THREADS = 100;//查找的线程数
		BlockingQueue<File> queue = new ArrayBlockingQueue<File>(FILE_QUEUE_SIZE);
		FileEnumerationTask enumerator = new FileEnumerationTask(queue, new File(directory));
		new Thread(enumerator).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("");//这个文件作为一个结束标记
	public FileEnumerationTask(BlockingQueue<File> queue,File startingDirectory){
		this.queue = queue;
		this.startingDirectory = startingDirectory;
	}
	public void run() {
		try {
			enumerate(startingDirectory);
			queue.put(DUMMY);//最后放入这个标记文件
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
	}
	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;
	
	public SearchTask(BlockingQueue<File>queue,String keyword) {
		this.queue = queue;
		this.keyword = keyword;
	}
	public void run() {
		boolean done = false;
		while(!done){
			try {
				File file = queue.take();
				if(file == FileEnumerationTask.DUMMY){
					queue.put(file);
					done = true;
				}else{
					search(file);
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}catch (IOException e) {
				e.printStackTrace();
			}
			
		}
	}
	public void search(File file)throws IOException{
		Scanner in = new Scanner(new FileInputStream(file));
		int lineNumber = 0;
		while(in.hasNextLine()){
			lineNumber ++;
			String line = in.nextLine();
			if(line.contains(keyword)){
				System.out.printf("%s:%d:%s%n",file.getPath(),lineNumber,line);
			}
		}
	}
}

 JAVA阻塞队列(BlockingQueue)实践_第1张图片

 

你可能感兴趣的:(BlockingQueue)