zoukankan      html  css  js  c++  java
  • Java多线程之join

    1.join方法只有在继承了Thread类的线程中才有。

    2.线程必须要start() 后再join才能起作用。

    将另外一个线程join到当前线程,则需要等到join进来的线程执行完才会继续执行当前线程。

    package Thread.join;
    
    class Sleeper extends Thread {
        private int duration;
    
        public Sleeper(String name, int sleepTime) {
            super(name);
            duration = sleepTime;
            start();
        }
    
        public void run() {
            try {
                sleep(duration);
            } catch (InterruptedException e) {
                System.out.println(getName() + " was interrupted."
                        + "isInterrupted():" + isInterrupted());
                return;
            }
            System.out.println(getName() + " has awakened");
        }
    }
    
    class Joiner extends Thread {
        private Sleeper sleeper;
    
        public Joiner(String name, Sleeper sleeper) {
            super(name);
            this.sleeper = sleeper;
            start();
        }
    
        public void run() {
            try {
                sleeper.join();
            } catch (InterruptedException e) {
                System.out.println("Interrupted");
            }
            System.out.println(getName() + " join completed");
        }
    }
    
    public class Joining {
        public static void main(String[] args) {
            Sleeper sleepy01 = new Sleeper("Sleepy01", 1500), sleepy02 = new Sleeper(
                    "Sleepy02", 1500);
            Joiner joiner01 = new Joiner("Joiner01", sleepy01), joiner02 = new Joiner("Joiner02",
                    sleepy02);
            joiner01.interrupt();
    
        }
    }
  • 相关阅读:
    Codeforces 758D:Ability To Convert(思维+模拟)
    Codeforces 758B:Blown Garland(模拟)
    BZOJ-1053 反素数
    BZOJ-1024 生日快乐
    BZOJ-1036 树的统计
    BZOJ-1029 建筑抢修
    BZOJ-1059 矩阵游戏
    BZOJ-1026 windy数
    BZOJ-1019 汉诺塔
    BZOJ-1031 字符加密
  • 原文地址:https://www.cnblogs.com/zhuawang/p/3751209.html
Copyright © 2011-2022 走看看