-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFutureTest.java
More file actions
127 lines (97 loc) · 2.64 KB
/
FutureTest.java
File metadata and controls
127 lines (97 loc) · 2.64 KB
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package Chapter14Thread.future;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
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 FutureTest {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.println("请输入文件名");
String dictionary=in.nextLine();
System.out.println("输入要查找的关键字:");
String keyword=in.nextLine();
MathCounter counter=new MathCounter(new File(dictionary), keyword);
FutureTask<Integer> task=new FutureTask<>(counter);
Thread t=new Thread(task);
t.start();
try {
System.out.println(task.get()+"matching files");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class MathCounter implements Callable<Integer>{
private File dictionary;
private String keyword;
private int count;
public MathCounter(File dic,String keyword){
this.dictionary=dic;
this.keyword=keyword;
}
public Integer call() throws Exception {
// TODO Auto-generated method stub
count=0;
try{
System.out.println("执行");
File[] files=dictionary.listFiles();
///////
List<Future<Integer>> results=new ArrayList<>();
for(File file:files){
//如果是目录的话,递归
if(file.isDirectory()){
MathCounter counter=new MathCounter(file, keyword);
//用FutureTask包装器把Callable转换成Future
FutureTask<Integer> task=new FutureTask<>(counter);
results.add(task);
//用FutureTask包装器把Callable转换成Runnable
Thread t=new Thread(task);
t.start();
}else{
if(search(file)){
count++;
}
}
for(Future<Integer> result:results){
try{
count+=result.get();
System.out.println("future里面结果::"+result.get());
}catch(ExecutionException e){
e.printStackTrace();
}
}
}
}catch(InterruptedException e){
System.out.println("产生中断异常");
}
return count;
}
//如果包含关键字,返回true
public boolean search(File file){
try{
try(Scanner in=new Scanner(file)){
boolean found=false;
while(in.hasNextLine()&&!found){
String line=in.nextLine();
if(line.contains(keyword)){
found=true;
}
}
return found;
}
}catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
}
}