结束线程方法1:使用退出标志

package com.mozq.thread.interrupt;
/**
 *     结束线程方法1:使用结束标志,但是当线程处于阻塞状态时,如果线程不退出阻塞状态,则无法检测退出标志,也就不能退出。
 * @author jie
 *
 */
class StopThread implements Runnable{
    private boolean exit = false;
    public void setExit(boolean exit) {
        this.exit = exit;
    }
    
    @Override
    public synchronized void run() {
        while(!exit) {
            //如果线程处于被阻塞状态,不退出阻塞状态,就无法检测退出标志,则无法通过退出标志退出。
            /*
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            */
            System.out.println(Thread.currentThread().getName() + "run...");
        }
        System.out.println(Thread.currentThread().getName() + "结束了...");
    }
}
public class MyInterrupt2 {
    public static void main(String[] args) {
        StopThread stopThread = new StopThread();
        Thread t = new Thread(stopThread);
        t.start();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //业务逻辑。。。
        //此处想结束线程
        stopThread.setExit(true);
    }
}
原文地址:https://www.cnblogs.com/mozq/p/10413601.html