Thread.join() 方法的使用

Thread.join() 方法的使用

  1. join作用:等待线程执行完毕,例子如下:例子1
  2. join时候被interrupt打断,会报异常InterruptException,例如B线程调用A线程同时使用了A.join()方法,A未执行完毕B被interrupt,则会抛出interrupt异常
  3. join(long):只等待long时间,与sleep类似 指定时间线程未执行完主线程会继续向下执行。 如果在long时间内A线程执行完且只花费 t 时间(t<long),则线程执行完毕,long时间还没到 主线程也会继续向下执行。例2。内部使用wait(long) 实现
  4. join 与 sleep 的区别,sleep不会释放锁,其他线程不可调用带有synchronize方法,join是用wait实现的会释放锁,其他线程可以调用带synchronize的方法。
  5. T.join(long)方法是带锁的方法,此方法的加锁对象是 T,若其他也对此进行加锁,可能会出现争抢锁的情况。

例子1:join使用


class MyThread07 extends Thread {
    
    
    @Override
    public void run() {
    
    
        try {
    
    
            long time = (long) (Math.random() * 1000);
            System.out.println(time);
            Thread.sleep(time);
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
    }
}

public class StudyThreads07join方法的使用 {
    
    
    public static void main(String[] args) throws InterruptedException {
    
    
        MyThread07 myThread07 = new MyThread07();
        myThread07.start();
        myThread07.join();
        System.out.println("我想在myThread07执行完毕后执行。。。");
        System.out.println("join 方法可以实现。。。");
    }
}

例2:

class MyThread07 extends Thread {
    
    
    @Override
    public void run() {
    
    
        try {
    
    
            long time = (long) (Math.random() * 1000);
            System.out.println(time);
            Thread.sleep(2000);
            System.out.println("线程执行完毕。。。");
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
    }
}

public class StudyThreads07join方法的使用 {
    
    
    public static void main(String[] args) throws InterruptedException {
    
    
        MyThread07 myThread07 = new MyThread07();
        myThread07.start();
        // 规定时间内 myThread07 没有执行完毕也会继续向下执行,类似超时
        // 如果myThread07比规定时间提前结束,主线程直接继续向下执行,
        myThread07.join(10000);
        System.out.println("我想在myThread07执行完毕后执行。。。");
        System.out.println("join 方法可以实现。。。");
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43960044/article/details/121085428
今日推荐