您好,欢迎访问一九零五行业门户网

java中线程的中断与终止

线程的中断与终止
1、interrupt()、isinterrupted()、interrupted()的作用
中断就是线程的一个标识位,它表示一个运行中的线程是否被其他线程调用了中断操作,其他线程可以通过调用线程的interrupt()方法对其进行中断操作,线程可以通过调用isinterrupted()方法判断是否被中断,线程也可以通过调用thread的interrupted()静态方法对当前线程的中断标识位进行复位。
相关视频教程推荐:java在线视频
注意:不要认为调用了线程的interrupt()方法,该线程就会停止,它只是做了一个标志位。
如下:
public class interruptthread extends thread{ @override public void run() { //一个死循环 while (true){ system.out.println("interruptthread正在执行"); } }}public static void main(string[] args) throws interruptedexception { interruptthread interruptthread = new interruptthread(); interruptthread.start(); interruptthread.interrupt();//调用线程的interrupt() system.out.println("interruptthread是否被中断,interrupt = " + interruptthread.isinterrupted()); //此时isinterrupted()方法返回true}输出结果:interruptthread是否被中断,interrupt = trueinterruptthread正在执行interruptthread正在执行interruptthread正在执行//...
可以看到当你调用了线程的interrupt()方法后,此时调用isinterrupted()方法会返回true,但是该线程还是会继续执行下去。所以怎么样才能终止一个线程的运行呢?
2、终止线程的运行
一个线程正常执行完run方法之后会自动结束,如果在运行过程中发生异常也会提前结束;所以利用这两种情况,我们还可以通过以下三种种方式安全的终止运行中的线程:
2.1、利用中断标志位
前面讲到的中断操作就可以用来取消线程任务,如下:
public class interruptthread extends thread{ @override public void run() { while (!isinterrupted()){//利用中断标记位 system.out.println("interruptthread正在执行"); } }}
当不需要运行interruptthread线程时,通过调用interruptthread.interrupt()使得isinterrupted()返回true,就可以让线程退出循环,正常执行完毕之后自动结束。
2.2、利用一个boolean变量
利用一个boolean变量和上述方法同理,如下:
public class interruptthread extends thread{ private volatile boolean iscancel; @override public void run() { while (!iscancel){//利用boolean变量 system.out.println("interruptthread正在执行"); } } public void cancel(){ iscancel = true; }}
当不需要运行interruptthread线程时,通过调用interruptthread.cancel()使iscancel等于true,就可以让线程退出循环,正常执行完毕之后自动结束,这里要注意boolean变量要用volatile修饰保证内存的可见性。
2.3、响应interruptedexception
通过调用一个线程的 interrupt() 来中断该线程时,如果该线程处于阻塞、限期等待或者无限期等待状态,那么就会抛出 interruptedexception,从而提前结束该线程,例如当你调用thread.sleep()方法时,通常会让你捕获一个interruptedexception异常,如下:
public class interruptthread extends thread{ @override public void run() { try{ while (true){ thread.sleep(100);//thread.sleep会抛出interruptedexception system.out.println("interruptthread正在执行"); } }catch (interruptedexception e){ e.printstacktrace(); } }}
当不需要运行interruptthread线程时,通过调用interruptthread.interrupt()使得 thread.sleep() 抛出interruptedexception,就可以让线程退出循环,提前结束。在抛出interruptedexception异常之前,jvm会把中断标识位复位,此时调用线程的isinterrupted()方法将会返回false。
java相关文章教程推荐:java编程入门
以上就是java中线程的中断与终止的详细内容。
其它类似信息

推荐信息