interrupt方法并不是强制终止线程,它只能设置线程的interrupted状态,而在线程中一般使用一下方式:
while (!Thread.currentThread().isInterrupted() && more work to do)
{...}
而被block的线程(sleep() or join())在被调用interrupt时会产生InterruptException,此时是否终止线程由本线程自己决定。程序的一般形式是:
public void run()
{
try
{
. . .
while (!Thread.currentThread().isInterrupted() && more work to do)
{
do more work
}
}
catch(InterruptedException e)
{
// thread was interrupted during sleep or wait
}
finally
{
cleanup, if required
}
// exiting the run method terminates the thread
}
运行这个程序,我们发现调用interrupt()后,程序仍在运行,如果不强制结束,程序将一直运行下去,如下所示:
......
I am running!
I am running!
I am running!
I am running!
****************************
Interrupted Thread!
****************************
I am running!
I am running!
I am running!
I am running!
I am running!
....