2012-10-12 45 views
1

我想在线程中每隔2秒向服务器发送请求,并检查是否有东西给我回给我....为了获得价值,我必须使用可调用。我无法弄清楚如何在每2秒运行调用线程,并获得价值从回来...这里是可调用的执行我的示例代码...可调用接口Loop stop主要方法进一步执行

public String call(){ 
    boolean done = true; 
    String returnData = ""; 
    while(done){ 
     try { 
      returnData = post.getAvailableChat(); 
      if(!returnData.equals("")){ 
       System.out.println("Value return by server is "+returnData); 
       return returnData; 
      } 
      return null; 
     } catch (IOException ex) { 
      done = false; 
      Logger.getLogger(GetChatThread.class.getName()).log(Level.SEVERE, null, ex); 
     } 

现在,这里是我的主类代码我知道我做错了这里的主类,因为我的代码不会去下一行while循环之后....但请告诉我该怎么办呢

Callable<String> callable = new CallableImpl(2);     

    ExecutorService executor = new ScheduledThreadPoolExecutor(1); 
    System.err.println("before future executor");      
    Future<String> future;           

    try {               
     while(chatLoop_veriable){          
      future = executor.submit(callable);       
      String serverReply = future.get();      
      if(serverReply != null){        
       System.out.println("value returned by the server is "+serverReply); 
       Thread.sleep(2*1000);        
      }//End of if            
     }//End of loop            
    } catch (Exception e) {           

回答

3

你正确地选择了一个ScheduledThreadPoolExecutor,但是你没有利用它提供的方法,特别是在你的情况下:scheduleAtFixedRate而不是提交。然后您可以删除睡眠部分,因为执行者将为您处理安排。

+0

我会尽力而且比标记你的答案有效......谢谢你的帮助...... –

0

Future.get()阻止这样的控制不会返回在此之后,直到线程完成。你应该使用Future.get(long timeout,TimeUnit unit)

future.get(2, TimeUnit.SECONDS); 
+0

OK兄弟我会试试看... Thankyou –

0

我认为它应该更像这从API文档 (注意有没有“公共”修饰符所以它可能需要一个嵌套的子类,或者一些相似解决的访问级别变量 的),它应该像.....

Callable<String> call(){ 
// code for the 2000 millisecond thread Callable is some sort of data/process for 
// a thread to "do" 
return (Callable<String>)callable; // or 1 
} 

然而,java.util.concurrent.Executors似乎是如何与赎回 附注五,实现的是一个向量作为API文档。

+0

V是一个向量?为什么演员扮演Callable角色? – assylias