Java中线程停止的三种方法
线程停止有三种比较常见的方法
1.设置标志位
这种方法比较简单易懂,不涉及到一些特定的方法
弊端:此方法无法解决线程阻塞时停止的问题
解决思路:
- 设置flag标志位并且给其赋初值 flag = true;
- 在加锁前判断 flag是否为 true,如果不是则不进入循环
- 在想要让其停止的地方将标志位设为false即可时线程停止
class MyThread implements Runnable {
private boolean flag = true;
public void run() {
int i = 1;
while (flag) {
try {
Thread.sleep(1000);
System.out.println("第"+i+"次执行,线程名称
为:"+Thread.currentThread().getName());
i++;
} catch (InterruptedException e) {
System.Out.println("异常!");
e.printStackTrace();
}
}
}
public void setFlag(boolean flag) {
this.flag = flag;
}
}
public class Test {
public static void main(String[] args) throws InterruptedException {
MyThread myThread = new MyThread();
Thread thread1 = new Thread(myThread,"子线程A");
thread1.start();
Thread.sleep(2000);
//设置标志位
myThread.setFlag(false);
System.out.println("代码结束");
}
}
2.调用Thread类提供的stop方法强制关闭线程
不管本次执行是否完毕,都强行关闭
此时其余代码不变,只将主函数改变
弊端:会产生不完整数据
public class Test {
public static void main(String[] args) throws InterruptedException {
MyThread myThread = new MyThread();
Thread thread1 = new Thread(myThread,"子线程A");
thread1.start();
Thread.sleep(2000);
//调用Thread类提供的stop方法强行关闭线程
thread.stop();
System.out.println("代码结束");
}
}
3.调用Thread类提供的interrupt()(最常用!)
使用interrupt方法停止线程有以下两种情况:
a.若线程中 没有使用类似sleep/wait/join这三种方法,调用此线程对象的interrupt方法并不会真正中断线程,只是简单的将线程的状态置为interrupt而已,我们可以根据此状态来进一步确定如何处理线程。
Thread类中提供的public boolean isInterrupted()可以检测当前线程状态是否为中断状态
class ThreadShutdown implements Runnable {
private boolean flag = true;
public void setFlag(boolean flag) {
this.flag = flag;
}
@Override
public void run() {
int i = 0;
while (flag) {
// Thread类中提供的public boolean isInterrupted()
// 可以检测当前线程状态是否为中断状态
boolean bool = Thread.currentThread().isInterrupted();
//interrupt方法停止程序
if(bool){
System.out.println("线程已被中断");
return;
}
System.out.println("当前线程的状态为"+bool);
System.out.println(
Thread.currentThread().getName()+ "," + i++);
}
System.out.println("线程停止");
}
}
public class ThreadStop{
public static void main(String[] args) throws InterruptedException {
ThreadShutdown threadShutdown = new ThreadShutdown();
Thread thread = new Thread(threadShutdown);
thread.start();
Thread.sleep(1000);
//调用Thread类提供的interrupt()
thread.interrupt();
}
}
b.若线程中调用了阻塞线程的方法:sleep(),wait(),join(),此时再调用interrupt方法时会抛出一个异常(InterruptedException),
同时将线程状态还原(isInterrupt = false)