停止线程思路
- 使用退出标志,使线程正常退出,也就是当run方法完成后线程终止。
- 使用stop方法强行终止线程(这个方法不推荐使用,因为stop和suspend、resume一样,也可能发生不可预料的结果)。
- 使用interrupt方法中断线程。(表示让当前等待的线程直接抛出异常)
代码如下:
package com.newDemo.controller.test;
class stopThread extends Thread{
private volatile boolean flag = true;
public void run(){
System.out.println("子线程开始....");
while (flag) {
try {
wait();
} catch (InterruptedException e) {
// e.printStackTrace();
stopThread();
}
}
System.out.println("子线程结束....");
}
public void stopThread() {
flag = false;
}
}
public class threadDemo19 {
public static void main(String[] args) {
stopThread stopThread = new stopThread();
stopThread.start();
for (int i = 1; i < 10; i++) {
try {
Thread.sleep(1000);
System.out.println("i:" + i);
if (i == 8) {
// stopThread.stopThread();
//表示让当前等待的线程直接抛出异常
stopThread.interrupt();
}
} catch (Exception e) {
// TODO: handle exception
}
}
}
}
这样的话,就能够让当前子线程停止,但是主线程还在继续,所以这个时候要注意,不要以为代码是错误的。