中断线程的方法分享

中断线程的方法分享

转自:

http://www.java265.com/JavaCourse/202204/3189.html

在java中我们引入中断的目的是为了打断线程现在所处的某种状态,但是我们知道这种状态一定是阻塞状态; 
在线程阻塞的时候,我们想要改变它阻塞的状态,所以通常在线程sleep,wait,join的情况下我们可以使用中断; 
由于中断可以捕获,通过这种方式我们可以结束线程; 
中断不是结束线程,只不过发送了一个中断信号而已,线程要退出还要我们加上自己的结束线程的操作。 

下文笔者讲述使用Java代码中断线程的方法分享,如下所示:

实现思路:
    使用interrupt()方法进行线程中断
在中断前,我们可使用isInterrupted()方法,判断一下线程是否已中断
package com.java265.other;
public class Test16 {
    public static void main(String[] args) throws Exception {
        MyThread2 a = new MyThread2();
        // 启动线程
        a.start();
        try {
            Thread.sleep(2000);
        } catch (InterruptedException x) {
        }
        System.out.println("in main() - 中断其他线程");
        a.interrupt();
        System.out.println("in main() - 离开");
    }
}

class MyThread2 extends Thread {
    public void run() {
        try {
            System.out.println("in run() - 将运行 work() 方法");
            work();
            System.out.println("in run() - 从 work() 方法回来");
        } catch (InterruptedException x) {
            System.out.println("in run() - 中断 work() 方法");
            return;
        }
        System.out.println("in run() - 休眠后执行");
        System.out.println("in run() - 正常离开");

    }

    public void work() throws InterruptedException {
          while (true) {
             if (Thread.currentThread().isInterrupted()) {
                System.out.println("C isInterrupted()=" + Thread.currentThread().isInterrupted());
                Thread.sleep(2000);
                System.out.println("D isInterrupted()=" + Thread.currentThread().isInterrupted());
             }
          }
        }
}

-----运行以上代码,将输出以下信息-----
in run() - 将运行 work() 方法
in main() - 中断其他线程
in main() - 离开
C isInterrupted()=true
in run() - 中断 work() 方法
hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 » 中断线程的方法分享