zoukankan      html  css  js  c++  java
  • java 多线程(1) Thread.join()

    1、为什么要使用Join()?

      因为在很多情况下,主线程生成并起动了子线程,如果子线程里要进行大量的耗时的运算,主线程往往将于子线程之前结束,但是如果主线程处理完其他的事务后,需要用到子线程的处理结果,也就是主线程需要等待子线程执行完成之后再结束,这个时候就要用到join()方法了。

    2、使用方法:

    public strictfp class Main{
        public static void main(String[] args) throws InterruptedException{
            Main main=new Main();
            Thread threadA=new Thread(main.new ThreadA());
            Thread threadB=new Thread(main.new ThreadB());
            threadA.start();
            threadA.join();
            threadB.start();
        }
        class ThreadA implements Runnable
        {
    
            @Override
            public void run() {
                // TODO Auto-generated method stub
                for(int i=0;i<10;i++)
                {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.println('A');
                }
            }
            
        }
        
        class ThreadB implements Runnable
        {
    
            @Override
            public void run() {
                // TODO Auto-generated method stub
                for(int i=0;i<10;i++)
                {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.println('B');
                }
            }
            
        }
    }

    输出

      

    A
    A
    A
    A
    A
    A
    A
    A
    A
    A
    B
    B
    B
    B
    B
    B
    B
    B
    B
    B

    如果这里没有使用join()的话,就会出现交叉ABABABABABABABABABAB.

    join可以让主线程等待子线程执行完再运行。

    3、面试题:

    1)现在有T1、T2、T3三个线程,你怎样保证T2在T1执行完后执行,T3在T2执行完后执行?

    这个线程问题通常会在第一轮或电话面试阶段被问到,目的是检测你对”join”方法是否熟悉。这个多线程问题比较简单,可以用join方法实现。

  • 相关阅读:
    0593. Valid Square (M)
    0832. Flipping an Image (E)
    1026. Maximum Difference Between Node and Ancestor (M)
    0563. Binary Tree Tilt (E)
    0445. Add Two Numbers II (M)
    1283. Find the Smallest Divisor Given a Threshold (M)
    C Primer Plus note9
    C Primer Plus note8
    C Primer Plus note7
    C Primer Plus note6
  • 原文地址:https://www.cnblogs.com/maydow/p/4897321.html
Copyright © 2011-2022 走看看