中断当前的线程,可以使用标志位停止,但是如果阻塞了永远不会中断,采用interrupt方法可以将阻塞状态变成中断状态,但是并不会停止线程,所以需要将状态转变过后还得通过标志位停止
class StopThread extends Thread {
// flag為true 线程一直运行状态 flag 停止线程
public boolean flag = true;
@Override
public synchronized void run() {
while (flag) {
try {
wait();
} catch (Exception e) {
//在这里停止线程,如果这里不调用不停止的话进程不会停止
stopThread();
}
System.out.println(Thread.currentThread().getName() + "----我是子线程");
}
}
public void stopThread() {
flag = false;
System.out.println(getName()+"---线程被停止掉了");
}
}
public class StopThreadDemo {
public static void main(String[] args) {
StopThread stopThread1 = new StopThread();
StopThread stopThread2 = new StopThread();
stopThread1.start();
stopThread2.start();
for (int i = 0; i < 30; i++) {
try {
Thread.sleep(10);
} catch (Exception e) {
// TODO: handle exception
}
System.out.println("main ...." + i);
if (i == 29) {
// stopThread1.stopThread();
// stopThread2.stopThread();
//将阻塞状态变成中断状态,进入新循环
stopThread1.interrupt();
stopThread2.interrupt();
}
}
}
}
线程关闭成功