虽然有Thread.stop方法,但该方法是不被推荐使用的,我们可以利用上面休眠与唤醒的机制,让线程在处理IterruptedException时,结束线程。
复制代码 代码如下:
Thread.interrupt示例
public class StopThreadSample {
public static void main(String[] args) throws InterruptedException
{
stopTest();
}
private static void stopTest() throws InterruptedException
{
Thread thread = new Thread()
{
public void run()
{
System.out.println("线程运行中。");
try
{
Thread.sleep(1*60*1000);
}
catch(InterruptedException ex)
{
System.out.println("线程中断,结束线程");
return;
}
System.out.println("线程正常结束。");
}
};
thread.start();
Thread.sleep(500);
thread.interrupt();
}
}
|