Killing thread after some specified time limit in

2019-01-02 15:13发布

Is there a way to kill a child thread after some specified time limit in Java? Edit: Also this particular thread may be blocked in its worst case (Thread is used to wait for a file modification and blocks until this event occurs), so im not sure that interrupt() will be successful?

8条回答
临风纵饮
2楼-- · 2019-01-02 16:02

Killing a thread is generally a bad idea for reasons linked to for the API docs for Thread.

If you are dead set on killing, use a whole new process.

Otherwise the usual thing is to have the thread poll System.nanoTime, poll a (possible volatile) flag, queue a "poison pill" or something of that nature.

查看更多
冷夜・残月
3楼-- · 2019-01-02 16:13

Not directly; I think the simplest way is to join() on that thread with that time limit, and interrupt the thread if it's not done by the time the join ended.

So,

Thread t = ...
t.join(timelimit);
if (t.isAlive) t.interrupt();

Notice I used interrupt instead of actually killing it, it's much safer. I would also recommend using executors instead of directly manipulating threads.

查看更多
登录 后发表回答