Use of Thread.join() method

Use of Thread.join() method

  1. Join function: wait for the thread to finish executing, the example is as follows: Example 1
  2. When the join is interrupted by interrupt, an exception InterruptException will be reported. For example, when thread B calls thread A and uses the A.join() method at the same time, if A is not finished executing and B is interrupted, an interrupt exception will be thrown.
  3. join(long): Only wait for a long time, similar to sleep, the specified time thread will continue to execute downwards before the main thread has finished executing. If the A thread is executed within the long time and only takes t time (t<long), the thread execution is completed, and the main thread will continue to execute downward before the long time has elapsed. Example 2. Internally implemented using wait(long)
  4. The difference between join and sleep is that sleep will not release the lock, other threads cannot call the method with synchronize, join is implemented with wait and will release the lock, and other threads can call the method with synchronize.
  5. The T.join(long) method is a method with a lock. The lock object of this method is T. If other locks are also applied to this method, there may be a situation of contention for locks.

Example 1: join use


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 方法可以实现。。。");
    }
}

Example 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 方法可以实现。。。");
    }
}

Guess you like

Origin blog.csdn.net/weixin_43960044/article/details/121085428