How to timeout a thread

后端 未结 17 1370
时光说笑
时光说笑 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:27

    I think you should take a look at proper concurrency handling mechanisms (threads running into infinite loops doesn't sound good per se, btw). Make sure you read a little about the "killing" or "stopping" Threads topic.

    What you are describing,sound very much like a "rendezvous", so you may want to take a look at the CyclicBarrier.

    There may be other constructs (like using CountDownLatch for example) that can resolve your problem (one thread waiting with a timeout for the latch, the other should count down the latch if it has done it's work, which would release your first thread either after a timeout or when the latch countdown is invoked).

    I usually recommend two books in this area: Concurrent Programming in Java and Java Concurrency in Practice.

提交回复
热议问题