【发布时间】:2016-03-30 01:09:06
【问题描述】:
我已经为一个简单的 Maze 项目工作了一段时间,我已经到了需要将 Callable 接口用作线程的地步。实现并运行后,我注意到虽然可调用类在后台运行,但我似乎无法在后台执行任何其他操作,例如输入。
我做了一个小项目来强调这个问题,看到当可调用类工作 10 秒时,我不能同时接受任何输入。 这是代码:
主类
public class Main {
static ExecutorService service = null;
static Future<String> task = null;
public static void main(final String[] argv) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("please enter a command");
String string = in.readLine();
while (!string.equals("exit")) {
if (!string.equals("command")) {
System.out.println("command not found");
} else {
service = Executors.newFixedThreadPool(1);
task = service.submit(new Foo());
try {
final String str;
// waits the 10 seconds for the Callable.call to finish.
str = task.get(); // this raises ExecutionException if
// thread dies
System.out.println(str);
service.shutdownNow();
} catch (final InterruptedException ex) {
ex.printStackTrace();
} catch (final ExecutionException ex) {
ex.printStackTrace();
}
}
string = in.readLine();
}
//
}
}
可调用类:
class Foo implements Callable<String> {
@Override
public String call() {
try {
// sleep for 10 seconds
Thread.sleep(10 * 1000);
} catch (final InterruptedException ex) {
ex.printStackTrace();
}
return ("Hello, World!");
}
}
【问题讨论】:
-
Callable是一个任务 -
// sleep for 10 secondsThread.sleep(5 * 1000);不写评论总比写错cmets好。幸运的是,这一点非常明显。 -
task.get()等待后台线程完成。 (你可以从下面的两个答案中推断出来,即使他们没有直接说出来。)
标签: java multithreading threadpool callable