java中原来在thread中提供了stop()方法来终止线程,但这个方法是不安全的,所以一般不建议使用。
本文向大家介绍使用interrupt方法中断线程。
使用interrupt方法来终端线程可分为两种情况:
(1)线程处于阻塞状态,如使用了sleep方法。
(2)使用while(!isinterrupted()){……}来判断线程是否被中断。
在第一种情况下使用interrupt方法,sleep方法将抛出一个interruptedexception例外,而在第二种情况下线程将直接退出。下面的代码演示了在第一种情况下使用interrupt方法
/*
author by w3cschool.cc
threadinterrupt.java
*/public class threadinterrupt extends thread {
public void run()
{
try
{
sleep(50000); // 延迟50秒
}
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("在50秒之内按任意键中断线程!");
system.in.read();
thread.interrupt();
thread.join();
system.out.println("线程已经退出!");
} }
以上代码运行输出结果为:
在50秒之内按任意键中断线程!
sleep interrupted
线程已经退出!
以上就是java 实例 - 终止线程的内容。