多线程 interrupt

多线程 interrupt

interrupt是从外部手动控制线程执行的方法。比如:下载资源线程A 调用了 下载图像线程B下载音频线程C线程a实时监控着磁盘的容量,如果资源量占磁盘99%,就必须停止线程b线程c的下载动作了;类似这种情况,可采用线程a调用线程b线程cinterrupt的方法主动停止线程b线程c的执行,当然线程b线程c内部也必须对线程a的停止信号作出判断,两者配合才能实现功能;线程b线程c的停止动作依赖isInterrupted方法,isInterrupted方法返回bool类型,默认是false,当线程a调用线程b线程cinterrupt方法后,线程b线程c调用isInterrupted方法返回true。举例如下

/*用文件替代磁盘,demo的run方法一直向文件写数据*/
public class Demo implements Runnable{
  @Override
  public void run() {
    try {
      	File file = new File("./1.txt");
        if (!file.exists())
            file.createNewFile();//若文件不存在,则创建
        FileOutputStream outputStream = new FileOutputStream(file);
        do{
            String s = LocalDate.now()+" "+ LocalTime.now()+ "\n";
            outputStream.write(s.getBytes());//向文件写数据
        }
        while (!Thread.currentThread().isInterrupted());//时刻监视Interrupt状态,一旦被修改,立刻终止循环
        outputStream.close();//关闭输出流
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
}

Main 监控文件大小,当文件大于2M时立刻停止线程a的写操作

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Demo demo = new Demo();
        Thread a = new Thread(demo, "thread a_");
        a.start();
        File file = new File("./1.txt");
        for(;;){
            if (file.length() >= 2*1024*1024 ){
                a.interrupt();//调用a线程的interrupt方法,手动停止线程执行
                break;
            }
        }
    }
}

特别提醒:interrupt 是一个必须被调用方和调用方双方配合使用的方法!

posted @ 2024-05-08 23:34  勤匠  阅读(18)  评论(0)    收藏  举报