多线程停止的方法
- 设置一个标志位。(无法处理线程阻塞时停止的问题)
- 调用Thread类提供的stop方法强行关闭线程。
这个方法已经不推荐使用了,因为会产生不完整的数据。
class ThreadDemo extends Thread{
private boolean flag=true;
public void setflag(boolean flag){
this.flag=flag;
}
@Override
public void run() {
while(flag){
System.out.println("李明建是头猪");
}
}
}
public class Solution {
public static void main(String[] args) throws InterruptedException {
Thread th1=new ThreadDemo();
th1.start();
Thread.sleep(1000);
th1.stop();
}
}
- 调用Thread类提供的interrupt();
a.若线程中没有使用类似sleep/wait/join时,调用此线程对象的interrupt方法并不会中断线程,只是简单地将线程的状态置为interrupt而已,我们可以根据此状态来进一步确定如何处理线程。
Thread类提供的public boolean isInterrupted()可以检测当前线程状态是否为中断状态。
b.若线程中调用了阻塞线程的方法sleep()/wait()/join(),此时再调用线程的interrupt方法时会抛出异常,同时将线程状态还原(isInterrupted=false)。
class ThreadDemo extends Thread{
@Override
public void run() {
while(!Thread.currentThread().isInterrupted()){
System.out.println("当前线程的状态"+Thread.currentThread().isInterrupted());
}
if(Thread.currentThread().isInterrupted())
System.out