Java 中有三种方法可以停止线程
- 通过退出标志,使程序正常的退出
- 通过使用stop方法强行终止线程,但不推荐,因为stop 是过期的方法
- 使用interrupt 方法终端线程, 但是interrupt()方法并不是马上停止线程, 而仅仅在当前线程打上一个停止的标记
首先先来了解一下 interrupted 和 isInterrupted 的区别
this.interrupted 测试当前线程是否已经中断
this.isInterrupted 测试线程是否已经中断
举个例子
package smaug.cloud.provider.thread.t5;
/**
* Created by naonao on 17/12/9.
*/
public class MyThread implements Runnable {
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println(i);
}
}
}
package smaug.cloud.provider.thread.t5;
/**
* Created by naonao on 17/12/9.
*/
public class MyTest {
public static void main(String[] args) throws InterruptedException {
MyThread t = new MyThread();
Thread thread = new Thread(t);
thread.start();
//Thread.sleep(3000);
//thread.interrupt();
Thread current = Thread.currentThread();
System.out.println(current.getName());
current.interrupt();
System.out.println(current.interrupted());
System.out.println(thread.interrupted());
System.out.println(current.isInterrupted());
}
}
得到的输出是
999
true
false
false
补充:
- this.interrupted 测试当前线程是否已经中断 所谓的当前线程 是指运行this.interrupted 这段代码的线程
- this.interrupted执行后具有将当前线程运行状态标记为false的功能
好了,我们知道 interrupted 是标志 是否终止线程,那么
package smaug.cloud.provider.thread.t6;
/**
* Created by naonao on 17/12/9.
*/
public class Thread6 implements Runnable {
@Override
public void run() {
for (int i = 0; i < 500; i++) {
if (Thread.interrupted()){
break;
}
System.out.println(i);
}
System.out.println("test");
}
}
这样是否就可以终止线程呢,我们来测试一下
package smaug.cloud.provider.thread.t6;
/**
* Created by naonao on 17/12/9.
*/
public class Test6 {
public static void main(String[] args) {
Thread6 thread6 = new Thread6();
Thread t = new Thread(thread6);
t.start();
t.interrupt();
}
}
得到的输出是
120
121
122
123
test
显然, break 后并没有终止线程,从for循环下面的那段代码可以看出,那么我们可以这么做
package smaug.cloud.provider.thread.t6;
/**
* Created by naonao on 17/12/9.
*/
public class Thread6 implements Runnable {
@Override
public void run() {
try {
for (int i = 0; i < 500; i++) {
if (Thread.interrupted()){
System.out.println("检测到终止了");
throw new InterruptedException();
}
System.out.println(i);
}
System.out.println("test");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
得到的输出
133
134
检测到终止了
java.lang.InterruptedException
at smaug.cloud.provider.thread.t6.Thread6.run(Thread6.java:13)
at java.lang.Thread.run(Thread.java:745)