繁体   English   中英

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

[英]How to run a task for a specific amount of time

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

//...
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 秒。 我怎么解决这个问题? 我也对其他方法持开放态度。

你可以试试:

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所以你应该处理这个异常。 看到 这个帖子

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM