方式一
使用退出标识,使得线程正常退出,即当run方法完成后进程终止。
public class TestFlagStop implements Runnable{
//1、设置一个标示位
private boolean flag = true;
@Override
public void run() {
int i = 0;
while(flag) {
System.out.println("run...Thread"+i++);
}
}
//2、设置一个公共的方法停止线程,转换标志位
public void stop() {
this.flag = false;
}
public static void main(String[] args) {
TestFlagStop testStop = new TestFlagStop();
new Thread(testStop).start();
for (int i = 0; i < 1000; i++) {
System.out.println("main"+i);
if(i==900) {
//调用stop方法切换标志位,让线程停止
testStop.stop();
System.out.println("线程该停止了");
}
}
}
}
方式二
停止一个线程在之前老的JDK中使用的是Thread.stop()方法,但是后面发现这种处理方法是很危险而且不安全的,由于stop()方法已经在JDK中被标明是“作废/过期”的方法,显然它在功能上是具有缺陷的。这里直接遗弃掉即可。
方式二
使用interrupt方法中断线程。
首先我们用for-break配合interrupt方式停止线程:
public class InterruptBreakStop extends Thread {
@Override
public void run() {
for (int i = 0; i < 500000; i++) {
if (this.isInterrupted()) {
System.out.println("已经是停止状态了!我要退出了!");
break;
}
System.out.println("i=" + (i + 1));
}
System.out.println("我被输出,如果此代码是for又继续运行,线程并未停止!");
}
public static void main(String[] args) {
InterruptBreakStop thread = new InterruptBreakStop();
thread.start();
try {
Thread.sleep(2000);
thread.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("end!");
}
}
从这里可以发现,break只是跳出for循环,而for循环之后的代码照常会运行!
为了解决这种问题,可以采用return的方式终止线程。
public class InterruptReturnStop extends Thread {
@Override
public void run() {
while (true) {
if (this.isInterrupted()) {
System.out.println("停止了!");
return;
}
System.out.println("time=" + System.currentTimeMillis());
}
}
public static void main(String[] args) throws InterruptedException {
InterruptReturnStop thread=new InterruptReturnStop();
thread.start();
thread.sleep(2000);
thread.interrupt();
}
}
输出结果:
一般推荐抛异常的方式,这样才能使得线程停止得以扩散。
public class InterruptExceptionStop extends Thread {
@Override
public void run() {
try {
while (true) {
if (this.isInterrupted()) {
System.out.println("停止了!");
throw new InterruptedException();
}
System.out.println("time=" + System.currentTimeMillis());
}
} catch (InterruptedException e) {
System.out.println( "抛异常了" );
e.printStackTrace();
}
}
public static void main(String[] args){
InterruptExceptionStop thread=new InterruptExceptionStop();
thread.start();
try {
thread.sleep(2000);
thread.interrupt();
} catch (InterruptedException e) {
System.out.println( "抛异常了呀" );
e.printStackTrace();
}
}
}
注意:
如果在sleep状态下使用interrupt()停止某一线程,会进入catch语句,并且清除停止状态值,使之变为false。可以理解为互斥关系,一旦使用这个interrupt方法,就不能让线程进入休眠状态。否则就会报这个错误。