java线程中止有三种方式:
- 直接使用stop()方法,已经弃用,不建议使用。
- 自定义volatile boolean类型变量作为中止标识。
package stop;
public class ThreadStop1 {
public static class MyThread extends Thread{
private volatile boolean start=true;
@Override
public void run() {
while(start){
doTask();
}
}
private void doTask(){
System.out.println("do some work");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void shutDown(){
start=false;
}
}
public static void main(String[] args) {
MyThread t1=new MyThread();
t1.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
t1.shutDown();
}
}
- 使用interrupted()方法
Thread.currentThread().interrupted()获取线程的中断标志,并重置。isInterrupted() 获取线程中断标志,不重置。interrupt()将目标线程的中断标记设置为true,在一些catch InterruptedException的方法中抛出异常。
下面看一个小栗子:
可以想一下程序打印的结果,他会打印after吗?
public class StopTest {
public static void main(String[] args) {
Thread t = new Thread(() -> {
System.out.println("before");
// if (!Thread.interrupted()){
System.out.println("in");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("after");
// }
});
t.start();
t.interrupt();
}
}
来看下结果:线程还是会打印after,
改进一下:
ublic class StopTest {
public static void main(String[] args) {
Thread t = new Thread(() -> {
try {
System.out.println("before");
Thread.sleep(100);
if (!Thread.interrupted()) {
System.out.println("in");
Thread.sleep(2000);
System.out.println("after");
}
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println();
}
});
t.start();
t.interrupt();
}
}
有错误还请指出!!!