java中有三种停止线程方法
1)使用退出标志,使线程正常退出,也就是当run方法完成后线程终止。
2)使用stop方法方法强行终止线程,但是不推荐使用这个方法,应为stop不安全而且已经被废弃的方法,还有suspend和resume都是废弃的方法。
3)使用interrupt方法中断线程。
讲解第三种interrupt()方法 仅仅使房钱线程中打了一个停止的标记,并不是真的停止线程。代码如下:
public class MyThread extends Thread {
@Override
public void run() {
super.run();
for (int i = 0; i < 500000; i++) {
System.out.println("i=" + (i + 1));
}
}
}
public class Run {
public static void main(String[] args) {
try {
MyThread thread = new MyThread();
thread.start();
Thread.sleep(2000);
thread.interrupt();
} catch (InterruptedException e) {
System.out.println("main catch");
e.printStackTrace();
}
}
}
线程没有停止,而是打印完i
再分析下线程是否是停止的状态
this.interrupted() 测试当前线程是否已经中断。
this.isInterrupted()测试线程是否已经中断。
两者区别:(小白还是不懂,如果大神们知道还请您给我留个言解答下☺)
如下代码展示:
public class MyThread extends Thread {
@Override
public void run() {
super.run();
for (int i = 0; i < 50000; i++) {
System.out.println("i=" + (i + 1));
}
}
}
public class Run {
public static void main(String[] args) {
try {
MyThread thread = new MyThread();
thread.start();
Thread.sleep(1000);
thread.interrupt();
//Thread.currentThread().interrupt();
System.out.println(thread.getName()+ " 是否停止1?="+thread.interrupted());
System.out.println(thread.getName()+ " 是否停止2?=