在Java中停止线程有以下三种方法可以终止正在运行的线程:
- 使用退出标志,使线程正常退出,也就是当run方法完成后线程终止。
- 使用stop方法强行终止线程,但是不推荐,可能产生不肯预料的结果。
- 使用interrupt中断线程。
调用线程的interrupt方法仅仅只是在线程中打一个停止的标志,不是真正的停止线程。
使用异常法终止线程
package exthread;
import java.io.BufferedWriter;
import java.io.FileWriter;
public class MyThread extends Thread {
public static BufferedWriter writer = null;
@Override
public void run() {
super.run();
try {
for (int i = 0; i < 500000; i++) {
if (this.isInterrupted()) {
System.out.println("interupt");
throw new InterruptedException("a");
}
writer.write("i=\n" + (i + 1));
}
} catch (Exception e) {
e.printStackTrace();
return;
}
}
public static void main(String[] args) {
try {
writer = new BufferedWriter(new FileWriter("time.txt"));
MyThread thread = new MyThread();
thread.start();
Thread.sleep(5);
thread.interrupt();
writer.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}
在sleep中终止进程
import java.io.BufferedWriter;
import java.io.FileWriter;
public class MyThread extends Thread {
public static BufferedWriter writer = null;
@Override
public void run() {
super.run();
try {
System.out.println("run begin, interrupt状态:" + currentThread().isInterrupted());
for (int i = 0; i < 500000; i++) {
writer.write("i=\n" + (i + 1));
}
Thread.sleep(200000);
System.out.println("run end");
} catch (Exception e) {
System.out.println("先停止,再遇到了sleep!进入catch!, interrupt状态:" + currentThread().isInterrupted());
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
writer = new BufferedWriter(new FileWriter("time.txt"));
MyThread thread = new MyThread();
thread.start();
Thread.sleep(5);
thread.interrupt();
writer.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}
如果在sleep状态下停止某一个线程,会进入catch语句,并且清除状态值,使之变为false。
所以一般在sleep状态如果线程被终端,需要重新设置中断标志。
private static void test4() throws InterruptedException {
Thread thread = new Thread(() -> {
while (true) {
// 响应中断
if (Thread.currentThread().isInterrupted()) {
System.out.println("Java技术栈线程被中断,程序退出。");
return;
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
System.out.println("Java技术栈线程休眠被中断,程序退出。");
Thread.currentThread().interrupt();
}
}
});
thread.start();
Thread.sleep(2000);
thread.interrupt();
}
判断线程是否是停止状态interrupted和isInterrupted方法:
Interrupted是测试当前线程是否已经是中断状态,执行后具有将状态标志置为false的功能。
isInterrupted检测thread对象是否已经是中断状态,但是不清除状态标志。