- 中断线程
- 执行完毕
- 修改判定标记
- 在catch中添加break
- 补充
要中断一个线程
1、让线程的入口方法执行完毕
2、使用Thread类提供的interrupt方法(如:把while中的判定标记改成基于Thread.currentThread().isInterrupted(),或者在catch里添加break,)
public class Demo05 {
static boolean isQuit = true ;
public static void main(String[] args) {
Thread t = new Thread(){
@Override
public void run() {
while (isQuit == true){
System.out.println("新线程");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
t.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("让线程中断");
isQuit = false;
}
}
修改判定标记
public class Demo06 {
public static void main(String[] args) {
Thread t = new Thread(){
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()){//判断当前线程是否中断
System.out.println("新线程");
}
}
};
t.start();
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
t.interrupt();
System.out.println("让线程中断");
}
}
在catch中添加break
public class Demo07 {
public static void main(String[] args) {
Thread t = new Thread(){
@Override
public void run() {
while (true){//判断当前线程是否中断
System.out.println("新线程");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
break;
}
}
}
};
t.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
t.interrupt();
System.out.println("让线程中断");
}
}
补充
调用interrupt方法时,可能会有两种情况
1、此时线程正处于休眠状态,那么此时直接出现休眠异常被catch到,执行catch中的代码,此时就可以在catch中添加break
2、线程没有处于休眠状态,那么此时就继续执行,这样就可以通过标志位Thread.currentThread().isInterrupted()来进行中断线程,如果有休眠状态则会休眠状态异常从而继续线程。
调用interrupt时,不一定就可以中断异常!!,具体还是要看代码逻辑
.如果线程没有调用 wait/join/sleep 等方法,interrupt()时,就会改变
Thread.currentThread()isInterrupted()的值,但不会改变Thread.interrupted() 的值
Thread.interrupted() 就相当于一个可以自动反弹的按钮,按下去就自动反弹上来(清楚标记)
Thread.currentThread()isInterrupted()就像一个普通按钮,按下去不会反弹



