-
Notifications
You must be signed in to change notification settings - Fork 0
/
BlockingQueueTest.java
99 lines (85 loc) · 2.41 KB
/
BlockingQueueTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
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){
Scanner in = new Scanner(System.in);
System.out.print("Enter base directory: ");
String directory = in.nextLine();
System.out.print("Enter key word: ");
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 enumerator = new FileEnumerationTask(queue, new File(directory));
new Thread(enumerator).start();
for(int i = 1; i <= SEARCH_THREADS; i++){
new Thread(new SearchTask(queue, keyword)).start();
}
}
}
class FileEnumerationTask implements Runnable{
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);
}
}
public static File DUMMY = new File("");
private BlockingQueue<File> queue;
private File startingDirectory;
}
class SearchTask implements Runnable{
public SearchTask(BlockingQueue<File> queue, String keyword){
this.queue = queue;
this.keyword = keyword;
}
public void run(){
try{
boolean done = false;
while(!done){
File file = queue.take();
if(file == FileEnumerationTask.DUMMY){
queue.put(file);
done = true;
} else {
search(file);
}
}
} catch (IOException e){
e.printStackTrace();
} catch (InterruptedException 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]%s:%d:%s\n", Thread.currentThread().getName(), file.getPath(), lineNumber, line);
}
}
in.close();
}
private BlockingQueue<File> queue;
private String keyword;
}