2016-08-04 54 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

感谢您的回复。这工作!!!!!我不确定,但逐渐我学会了:) –