2015-12-23 25 views
0

我一直在爲一個簡單的迷宮項目工作了一段時間,我到了需要使用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!"); 
    } 
} 
+0

'Callable'是一項任務 – Ramanlfc

+2

'//睡眠10秒'Thread.sleep(5 * 1000);'最好不要寫評論而不要寫錯誤的評論。幸運的是這個很明顯。 – StephaneM

+0

'task.get()'_waits_爲後臺線程完成。 (你可以從下面的兩個答案推斷出,即使他們沒有出來說出口。) –

回答

3

https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html#submit(java.util.concurrent.Callable)

如果您想立即阻塞任務的等待,你可以使用表格結果= exec.submit(aCallable)。獲得的結構();

這是你在做什麼(阻塞主線程等待一個任務)

+0

那麼使用這個接口的好處是什麼,如果我不能同時運行更多的線程,而這個工程呢? – liranahum

+0

您應該使用由executor.submit()返回的Future對象,然後可以在該元素上調用isDone()以知道操作何時完成。當isDone返回true時,你可以用get()得到結果(總是在Future對象上調用) – Massimo

1

我注意到,雖然可調用類在後臺運行,我似乎無法工作,什麼都在後臺

......討論......問題解釋...

現在使用這個界面似乎毫無意義。

我真的不知道你想幹什麼,但ExecutorServiceCallable整個點是在後臺執行任務。

但是「在後臺」是什麼意思?這意味着,當新線程關閉執行一些任務時,提交任務的線程可以執行其他操作

它看起來像這樣:

final ExecutorService executorService = Executors.newFixedThreadPool(NUM_THREADS); 

ReturnType doSomethingInTheBackground() { 

    // create the task object 
    Callable<ReturnType> task =() -> doSomething(); 

    // submit the task object 
    Future<ReturnType> future = executorService.submit(task); 

    doSomethingElse(); 

    // wait for the result. 
    return future.get(); 
} 

private ReturnType doSomething() { ... } 

private void doSomethingElse() { ... } 

doSomethingElse()電話是什麼讓一切都值得。如果調用線程除了等待結果(即調用future.get())之外沒有別的事情要做,那麼你是對的:使用多個線程沒有意義。調用線程只需要執行任務就簡單了。

相關問題