如何在特定时间内运行任务

时间:2018-08-19 11:06:01

标签: java time chat

我正在实现某种聊天应用程序,我需要一些帮助。这是简化的代码:

//...
Boolean stop = false;

while(!stop) {

    ServerRequest message = (ServerRequest) ois.readObject();
    broadcastMessage((String)message.getData()); //this method sends the client's message to all the other clients on the server

    stop = (System.nanoTime() - start >= handUpTime); // I want to let the client send his messages for no more than handUpTime seconds
} //...

我想让客户端将其消息发送到服务器一定时间(handUpTime),然后“阻止”他,但是我不知道如何以“优雅”的方式进行操作。当然,当系统等待接收消息时,我的代码偶然出现在ois.readObject()部分上,并继续运行超过handUpTime秒。我怎么解决这个问题?我也对其他方法持开放态度。

1 个答案:

答案 0 :(得分:1)

您可以尝试:

ExecutorService executorService = Executors.newSingleThreadExecutor();

Callable<Object> callable = () -> {
    // Perform some blocking computation
    return someObject
};

Future<Object> future = executorService.submit(callable);

Object result = future.get(YOUR_TIMEOUT, TimeUnit.SECONDS);

如果future.get()在一定时间内没有返回,则会抛出TimeoutException,因此您应该处理该异常。参见this post