线程类的join、interrupt等方法的使用详解

本文详细介绍了Java线程中的join、interrupt方法,包括它们的源码解析、使用示例和实际效果。join方法使得调用线程等待目标线程结束,而interrupt方法设置中断标志,当线程处于阻塞状态时调用会抛出InterruptedException。推荐通过变量状态控制或中断异常来优雅地停止线程。
摘要由CSDN通过智能技术生成

经常有人会问:如何停止一个线程?线程类Threadjoinsleepinterrupt等方法的具体使用场景是什么?本文就线程的joinsleep方法来看一下具体场景下的表现。

方法定义

join

先看下源码

/**
     * Waits for this thread to die.
     *
     * <p> An invocation of this method behaves in exactly the same
     * way as the invocation
     *
     * <blockquote>
     * {@linkplain #join(long) join}{@code (0)}
     * </blockquote>
     *
     * @throws  InterruptedException
     *          if any thread has interrupted the current thread. The
     *          <i>interrupted status</i> of the current thread is
     *          cleared when this exception is thrown.
     */
    public final void join() throws InterruptedException {
   
        join(0);
    }

源码中提示:Waits for this thread to die.顾名思义,等待线程死亡。
而且该方法会抛出中断异常
那么具体会产生什么效果呢?我们来验证一下。
以下代码是在主线程循环体内部调用其他线程的join方法,其他线程单纯的打印执行结果

/**
   * 程序入口,主线程
   */
public static void main(String[] args) {
   

    Thread thread = new Thread(new PrintTask("Thread"));
    thread.start();

    for (int i = 0; i < 1000; i++) {
   
      if (i == 500) {
   
        try {
   
          thread.join();
        } catch (InterruptedException e) {
   
          e.printStackTrace();
        }
      }
    }
    System.out.println("程序结束");
  }

/**
   * 子线程任务
   */
private static class PrintTask implements Runnable {
   

    private String name;

    public PrintTask(String name) {
   
      this.name = name;
    }

    @Override public void run() {
   
      for (int i = 0; i < 1000; i++) {
   
        System.out.println(name + " ------> " + i);
      }
      System.out.println("-----thread finished. -----");
    }
  }

执行以上main方法,输出为:

Thread ------> 995
Thread ------> 996
Thread ------> 997
Thread ------> 998
Thread ------> 999
-----thread finished. -----
程序结束

可以看出,主线程中调用其他线程的join后,必须等待其他线程的结束,才可以继续执行。
也就是说:

自身线程内,他线程join。自身需要等待他线程结束后才会获得执行,影响自身

稍微改动一下,将主线程的join操作移动到其他线程执行体内。

/**
   * 程序入口,主线程
   */
  public static void main(String[] args) {
   

    Thread thread = new Thread(new PrintTask("Thread"));
    thread.start();

    for (int i = 0; i < 1000; i++) {
   
      // 让主线程不要太快结束
      Math.random();
    }
    System.out.println("程序结束");
  }
  
  private static 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值