/**
* @author wenhui
* @description
* @Date 2019/11/16
*/
class StopThread extends Thread {
public boolean flag = true;
@Override
public synchronized void run() {
while (flag) {
try {
wait();
} catch (InterruptedException e) {
stopThread();
//e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
}
}
public void stopThread() {
this.flag = false;
System.out.println("---stopThread---");
}
}
public class StopThreadDemo {
public static void main(String[] args) {
StopThread stopThread = new StopThread();
stopThread.start();
try {
Thread.sleep(1000);
// stopThread.stopThread();
stopThread.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
运行结果: