How to timeout a thread

后端 未结 17 1142
时光说笑
时光说笑 2020-11-22 01:01

I want to run a thread for some fixed amount of time. If it is not completed within that time, I want to either kill it, throw some exception, or handle it in some way. How

17条回答
  •  故里飘歌
    2020-11-22 01:28

    Consider using an instance of ExecutorService. Both invokeAll() and invokeAny() methods are available with a timeout parameter.

    The current thread will block until the method completes (not sure if this is desirable) either because the task(s) completed normally or the timeout was reached. You can inspect the returned Future(s) to determine what happened.

提交回复
热议问题