-
Notifications
You must be signed in to change notification settings - Fork 4
/
TestExecutor.java
61 lines (53 loc) · 1.52 KB
/
TestExecutor.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
package concurrent;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
/**
* java �ṩ��Executor��ʵ�ֶ��߳�
* @author stoneFang
*
*/
public class TestExecutor {
public static void main(String[] args) {
ExecutorService executor = Executors.newSingleThreadExecutor();
ExecutorService fixExecutor = Executors.newFixedThreadPool(10);
Callable<List<String>> callable;
callable = new Callable<List<String>>(){
@Override
public List<String> call() throws Exception {
return readFile("src/concurrent/test.txt");
}
};
Future<List<String>> future = executor.submit(callable);
try {
List<String> lines = future.get(5, TimeUnit.SECONDS);
for(String line: lines) {
System.out.println(line);
}
} catch (InterruptedException | ExecutionException | TimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static List<String> readFile(String path){
List<String> listTxt = new ArrayList<String>();
File fileName = new File(path);
try {
InputStreamReader reader = new InputStreamReader(new FileInputStream(fileName));
BufferedReader buf = new BufferedReader(reader);
String line = "";
while(line != null) {
listTxt.add(line);
line = buf.readLine();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listTxt;
}
}