• Java:Thread:join()


    Java:Thread:join()方法加入一个线程

    在Java多线程中,如果某一个线程s在另一个线程t上调用t.join(),此线程s将被挂起,直到目标线程t结束才恢复(此时t.isAlive()返回为假)。

    也可以在调用join()时带上一个超时参数(单位可以是毫秒,或者毫秒和纳秒),这样如果目标线程在这段时间内还没有结束的话,join()方法总能返回。

    对join()方法的调用可以被中断,做法是在调用线程上调用interrupt()方法。

     1 class Sleeper extends Thread {
     2 
     3     private int duration;
     4     
     5     public Sleeper(String name, int sleepTime) {
     6         super(name);
     7         this.duration = sleepTime;
     8         start();
     9     }
    10     
    11     @Override
    12     public void run() {
    13         try {
    14             sleep(duration);
    15         } catch (InterruptedException e) {
    16             /** 异常被捕获时将清理线程的中断标识,因此在catch子句中isInterrupted()返回的值为false.*/
    17             System.out.println(getName() + "was interrupted. " + "isInterrupted(): " + isInterrupted());
    18             return ;
    19         }
    20         System.out.println(getName() + " has awakened.");
    21     }
    22     
    23 }
    24 
    25 
    26 class Joiner extends Thread {
    27     
    28     private Sleeper sleeper;
    29     
    30     public Joiner(String name, Sleeper sleeper) {
    31         super(name);
    32         this.sleeper = sleeper;
    33         start();
    34     }
    35     
    36     @Override
    37     public void run() {
    38         try {
    39             sleeper.join();
    40         } catch (InterruptedException e) {
    41             System.out.println("Interrupted.");
    42         }
    43         System.out.println(getName() + " join completed");
    44     }
    45     
    46 }
    47 
    48 
    49 public class JoinDemo {
    50     
    51     public static void main(String[] args) {
    52         Sleeper
    53             sleepy = new Sleeper("Sleepy", 1500),
    54             grumpy = new Sleeper("Grumpy", 1500);
    55         Joiner
    56             dopey = new Joiner("Dopey", sleepy),
    57             doc = new Joiner("Doc", grumpy);
    58         grumpy.interrupt();
    59     }
    60 
    61 }
    62 
    63 /**
    64  * 程序运行结果:
    65  * Grumpywas interrupted. isInterrupted(): false
    66  * Doc join completed
    67  * Sleepy has awakened.
    68  * Dopey join completed
    69  * 
    70  */
    JoinDemo.java

  • 相关阅读:
    如何获得刚刚插入数据的id
    Ado.net怎么执行存储过程?
    SqlServer存储过程,学习
    视图view
    CTE(公用表表达式)
    事务
    over()的用法
    Inno Setup 系列之安装、卸载前检测进程运行情况并关闭相应进程
    Inno Setup的常用脚本
    跟武哥一起学习Spring Boot
  • 原文地址:https://www.cnblogs.com/slowalker/p/3378035.html
Copyright © 2020-2023  润新知