1.new一个Callable<V>对象
2.用callable对象构造一个FutureTask<V>
3.用FutureTask对象构造一个Thread,并调用thread的start
4.调用FutureTask对象的get方法
下面的代码来自《java核心技术:卷1》
package test.futureTaskTest;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class Main {
public static void main(String[] args) {
// Scanner in = new Scanner(System.in);
// System.out.println("input dir:");
// String dir = in.nextLine();
// System.out.println("input key:");
// String key = in.nextLine();
String dir = "d:/logs", key = "2013";
MatchCallable match = new MatchCallable(new File(dir), key);
FutureTask<Integer> futureTask = new FutureTask<Integer>(match);
Thread t = new Thread(futureTask );
t.start();
try {
System.out.println(futureTask.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
static class MatchCallable implements Callable<Integer> {
private final File dir;
private final String key;
public MatchCallable(File dir, String key) {
this.dir = dir;
this.key = key;
}
@Override
public Integer call() throws Exception {
Integer count = 0;
File[] files = null;
try {
System.out.println("isDir:" + dir.isDirectory() + " isFile:" + dir.isFile() + " " + dir);
files = dir.listFiles();
List<FutureTask<Integer> > list = new LinkedList<FutureTask<Integer> >();
for (File file : files) {
if (file.isFile()) {
if (search(file))
++count;
} else {
MatchCallable match = new MatchCallable(file, key);
FutureTask<Integer> futureTask = new FutureTask<Integer>(match);
list.add(futureTask);
Thread t = new Thread(futureTask );
t.start();
}
}
for (FutureTask<Integer> ftask : list) {
count += ftask.get();
}
return count;
}catch (Throwable e) {
return count;
}
}
private boolean search(File file) {
boolean found = false;
try {
Scanner in = new Scanner(file);
while (!found && in.hasNextLine()) {
if (in.nextLine().contains(key)) {
found = true;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return found;
}
}
}