Java线程停止的方式
- 可以调用stop()方法,但是该方法已经被停用,同时该方法会使线程当前未完成的任务丢失
- 可以调用interrupt()方法标记当前线程为停止状态,在线程中调用isInterrupted()方法,如果该方法返回true,进行停止线程操作(return,throw),interrupt、interrupted 、isInterrupted 详解
下面演示线程的两种停止方法
stop()方法停止
public class ThreadStopTest {
public static void main(String[] args) {
StopThread stopThread = new StopThread();
Thread t = new Thread(stopThread);
t.start();
try {
Thread.sleep(50);
} catch (InterruptedException ignore) {
// ignore this exception
}
t.stop();
}
}
class StopThread implements Runnable {
@Override
public void run() {
System.out.println("thread is start");
for (int i = 0; i < 10000000; i++) {
System.out.println(i);
}
}
}
运行结果:
interrupt()方法停止
public class ThreadInterruptTest {
public static void main(String[] args) {
InterruptThread interruptThread = new InterruptThread();
Thread t = new Thread(interruptThread);
t.start();
try {
Thread.sleep(50);
} catch (InterruptedException ignore) {
// ignore this exception
}
t.interrupt();
}
}
class InterruptThread implements Runnable {
@Override
public void run() {
System.out.println("thread is start");
for (int i = 0; i < 10000000; i++) {
if (Thread.currentThread().isInterrupted()) {
return;
}
System.out.println(i);
}
}
}
运行结果: