Waiting for threads in multithreading

significance:

        Why wait for threads?

        Because multiple threads are executed concurrently, the specific execution process is scheduled by the operating system, and the process of scheduling threads by the operating system is "random", so we cannot determine the order in which threads are executed, so if we want threads to follow the specified order After execution, you need to use the concept of thread waiting

code:

package 等待线程;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: wuyulin
 * Date: 2023-07-25
 * Time: 13:51
 */
//通过join()方法让一个线程等待另一个线程
public class Demo1 {
    public static void main(String[] args) {
        Thread B=new Thread(()->{
            for(int i=0;i<5;i++){
                System.out.println("hello B");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println("B线程结束");
        });

        Thread A=new Thread(()->{
            for(int i=0;i<3;i++){
                System.out.println("hello A");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

            //到达此处时要是B线程还没有结束,A线程就会进入阻塞状态,等待B线程结束后才会将A线程恢复,继续执行下面的代码
            try {
                B.join();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            System.out.println("A线程结束");
        });



        A.start();
        B.start();
    }



}

main content:

        Let one thread wait for another thread through the join() method

Detailed analysis:

        Since the purpose of this program is to allow thread B to finish executing first, and then thread A to finish executing, it is necessary to add B.join() code to thread A. When the program in thread A executes to this code, if thread B still If it is not finished, the A thread will enter the blocking state, wait for the B thread to end before the A thread will resume, and continue to execute the following code, and if the B thread has ended at this time, then the A thread will not enter the blocking state and execute directly code behind

 
 
 

Guess you like

Origin blog.csdn.net/q322359/article/details/131917812