我一直在爲一個簡單的迷宮項目工作了一段時間,我到了需要使用Callable接口作爲線程的地步。在實現和運行後,我注意到,雖然可調用類在後臺運行,但我似乎無法在後臺運行其他任何操作,例如輸入。是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'是一項任務 – Ramanlfc
'//睡眠10秒'Thread.sleep(5 * 1000);'最好不要寫評論而不要寫錯誤的評論。幸運的是這個很明顯。 – StephaneM
'task.get()'_waits_爲後臺線程完成。 (你可以從下面的兩個答案推斷出,即使他們沒有出來說出口。) –