Java终止线程问题


如果一个线程要完成一个很长时间的job,要求要果30秒未完成就结束这个线程。在java中不用stop()和destroy()的情况下要怎么实现?

java 多线程

少年alice 10 years ago

@android 如何优雅的主动终止并等待线程的结束?
@java 中止正在运行的线程
@关于android关闭耗时线程是的问题

简单说, 线程自己监测 interrupted标志位, 外部线程调用thread.interrupt() 去试图中止此线程.

更新

java里, 没有很直接的方法, 可以安全的去中止运行中的进程. 必须让线程自己退出.

详细的说明见JCP 7.1 Task Cancellation, 简单的做点摘抄:

1). Interruption is usually the most sensible way to implement cancellation;
2). A good way to think about interruption is that it does not actually interrupt a running thread; it just requests that the thread interrupt itself at the next convenient opportunity. (These opportunities are called cancellation points.)
3). Object.wait(), Thread.sleep()等方法在得到interrupt请求后, 会抛出InterruptedException;
4). However, not all blocking methods or blocking mechanisms are responsive to interruption; if a thread is blocked performing synchronous socket I/O or waiting to
acquire an intrinsic lock, interruption has no effect other than setting the thread's interrupted status.

你的程序不可能每一步都去判断interrupted状态, 但是你可以定义自己的cancellation points, 在合适的时间(比如完成了某些子步骤)后去检查interrupted状态. 我记得在 unix pthread里也有类似的概念.

Glory answered 10 years ago

Your Answer