Java 如何终止线程呢?
下文笔者讲述java中终止线程的方法分享,如下所示:
实现思路:
1.可使用Thread中stop()方法即可终止线程
2.使用interrupt方法中断线程
注意事项:
Thread中stop()方法不安全,笔者不建议使用此种方法
interrupt方法中断线程注意事项:
使用interrupt方法后,sleep方法将抛出一个InterruptedException
或线程直接退出
例:
public class ThreadInterrupt extends Thread
{
public void run()
{
try
{
sleep(30000); // 延迟30秒
}
catch (InterruptedException e)
{
System.out.println(e.getMessage());
}
}
public static void main(String[] args) throws Exception
{
Thread thread = new ThreadInterrupt();
thread.start();
System.out.println("在30秒之内按任意键中断线程!");
System.in.read();
thread.interrupt();
Thread.join();
System.out.println("线程已经退出!");
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


