2016-08-04 32 views
0

我已經實現Service類的JavaFX的以下部分:實現服務類不運行

public void processingImage() { 

    Task<Void> track = new Task<Void>() { 

     @Override 
     protected Void call() throws Exception { 

      while (true) { 
       if (flag == false) { 
        if (someCondition) { 
         flag = true; 
         CommunicateServer.sendObject = new Object[2]; 
         CommunicateServer.sendObject[0] = 6; 
         CommunicateServer.sendObject[1] = "hello"; 

         myService.start(); 
         flag = false; 

         System.out.println("this line does not print"); 
       } 
      } 
      return null; 
     } 
    }; 
    Thread th1 = new Thread(track); 
    th1.setDaemon(true); 
    th1.start(); 
} 

而且MyService類爲:

private class MyService extends Service<Void> { 

    @Override 
    protected Task<Void> createTask() { 
     return new Task<Void>() { 
      @Override 
      protected Void call() throws Exception { 

        CommunicateServer.callSendObject(CommunicateServer.sendObject, true); 
        response = CommunicateServer.getObject(); 
        System.out.println("this print should have been many times but only executed once!!!!"); 

       return null; 
      } 
     }; 
    } 
} 

我的問題是,雖然我期待的代碼要打印this line does not print,代碼實際上不打印此。此外,行this print should have been many times but only executed once!!!!只打印一次,但我認爲應該打印多次。我不知道如何解決這個問題。任何幫助或建議都將以感恩的心情得到滿足。

回答

1

你不期望你的代碼能做什麼,但Service.start()should be called from the FX Application Thread。既然你是從後臺線程調用它,這可能會引發異常,從而阻止你到達System.out.println(...)聲明。

此外,該服務必須在READY狀態接收呼叫start(),所以在第二執行(如果有的話),因爲服務沒有被重置,你會得到一個IllegalArgumentException,退出call()方法在processingImage()中定義的任務中。因此,您的服務最多隻能執行一次。

+0

感謝您的回覆。這工作!!!!!我不確定,但逐漸我學會了:) –