简体   繁体   English

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

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

I'm implementing some sort of chat application and I need some help.我正在实施某种聊天应用程序,我需要一些帮助。 This is the simplified code:这是简化的代码:

//...
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
} //...

I want to let a client to send his messages to the server for a certain amount of time (handUpTime) and then "block" him, but I don't know how to do this in an "elegant" manner.我想让客户端将他的消息发送到服务器一段时间(handUpTime),然后“阻止”他,但我不知道如何以“优雅”的方式做到这一点。 Of course, my code stumbles upon the ois.readObject() part, as the System waits to receive a message, and continues to run for more than handUpTime seconds.当然,我的代码偶然发现了 ois.readObject() 部分,因为系统等待接收消息,并继续运行超过 handUpTime 秒。 How can I solve this problem?我怎么解决这个问题? I'm open to other approaches too.我也对其他方法持开放态度。

You can try:你可以试试:

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);

If the future.get() doesn't return in certain amount of time, it throws a TimeoutException so you should handle the exception.如果future.get()在一定时间内没有返回,它会抛出一个TimeoutException所以你应该处理这个异常。 See this post .看到 这个帖子

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

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