我试图在一个线程中每 2 秒向服务器发送一次请求,并检查是否有东西给我。我无法弄清楚如何每 2 秒运行一次可调用线程并从中获取价值……这是我的可调用实现示例代码……
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) {