一、如何让一个线程的停止呢?
让线程停止有三种方法:
1.设置标记位,使线程正常退出。
2.使用stop()方法强制退出(不建议使用)。
3.使用Thread类中提供interrupt()来中断线程。
1.1设置标记使线程退出
public class Mythread9 implements Runnable {
//设置标志位
private volatile boolean flag = true;
@Override
public void run() {
int i = 0;
while (flag) {
try {
Thread.sleep(1000);
i++;
System.out.println("线程:" + Thread.currentThread().getName() + "第" + i + "次执行");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void setFlag(boolean flag) {
this.flag = flag;
}
}
public class StopTest1 {
public static void main(String[] args) throws InterruptedException {
Mythread9 mythread9=new Mythread9();
Thread thread=new Thread(mythread9,"子线程");
thread.start();
Thread.sleep(2000);
mythread9.setFlag(false);
}
结果如下:
线程:子线程第1次执行
线程:子线程第2次执行
Process finished with exit code 0
1.2使用stop()方法
只需将上面程序的 mythread9.setFlag(false)替换成thread.stop().
从jdk1.2.后已经不建议使用stop(),因为stop会解除由线程获取的所有锁定,当在一个线程对象上调用stop()方法时,这个线程对象所运行的线程就会立即停止,假如一个线程正在执行;synchronized void { x = 3; y = 4;} 由于方法是同步的,多个线程访问时总能保证x,y被同时赋值,而如果一个线程正在执行到x = 3;时,被调用了 stop()方法,即使在同步块中,它也会马上stop了,这样就产生了不完整的残废数据。
1.3、使用Thread类中提供的interrupt()方法
调用线程类的interrupted方法,其本质只是设置该线程的中断标志,将中断标志设置为true,并根据线程状态决定是否抛出异常。因此,通过interrupted方法真正实现线程的中断原理是:开发人员根据中断标志的具体值,来决定如何退出线程。
public class MyThread10 implements Runnable {
private boolean flag = true;
@Override
public void run() {
int i = 1;
while (flag) {
try {
//这里阻塞之后,线程被调用了interrupte()方法,
Thread.sleep(1000);
//默认中断标志是false,
/*当调用interurupted,将
中断标志改为true,若非阻塞状态
则为true,并结束,当阻塞状态
重新设置为false,*/
boolean bool = Thread.currentThread().isInterrupted();
if (bool) {
System.out.println("非阻塞情况下执行该操作。。。线程状态" + bool);
break;
}
System.out.println("第"+i+"次执行,线程名称为:"+Thread.currentThread().getName());
i++;
} catch (InterruptedException e) {
System.out.println("退出了");
boolean bool = Thread.currentThread().isInterrupted();
System.out.println(bool);
return;
}
}
}
public void setFlag(boolean flag) {
this.flag = flag;
}
}
public class StopTest1 {
public static void main(String[] args) throws InterruptedException {
MyThread10 mythread=new MyThread10();
Thread thread=new Thread(mythread,"子线程");
thread.start();
Thread.sleep(1000);
//方法interrupt()只是给受阻塞的线程发出一个中断信号,这样受阻线程就得以退出阻塞的状态。
thread.interrupt();
}
}
结果如下:
第1次执行,线程名称为:子线程
退出了
false
Process finished with exit code 0