[Multithreading]-Detailed explanation of the use of join method

I. Introduction

According to convention, before we talk about a knowledge point, we habitually propose a business scenario application to help understand. Today we will talk about the relevant characteristics of join through a scumbag case:

Chen from the third class of civil engineering is a well-known scumbag. Recently, Chen broke up with his girlfriend. He was in the open window and opened the people near WeChat and picked a girl he thought was good-looking. Made a request to strike up a conversation.

public class ChatUp {
    
    
	// 被搭讪人是否回复
	public volatile static boolean flag = false;
	// 微信昵称
	public static String userName = "土木三班陈同学";

	public static void main(String[] args) throws InterruptedException {
    
    
		// 这天陈同学闲得无聊 打开附近的人进行搭讪
		Thread thread = new Thread(() -> {
    
    
			try {
    
    

				String msg = Thread.currentThread().getName() + "同学,你好像我认识的一个人!";
				// 陈同学发起搭讪
				say(userName, msg);
				Thread.sleep(1_000);
				// 蛋蛋同学回复
				say(Thread.currentThread().getName(), "像谁?");
				flag = true;
			} catch (InterruptedException e) {
    
    
			}
		}, "蛋蛋");
		thread.start();
		// 这里小小的休眠下 保证控制台输出顺序
		Thread.sleep(5l);
		// 判断是否回复了陈同学
		if (flag) {
    
    
			say(userName, "我的心上人!");
		} else {
    
    
			System.err.println("陈同学没有等到回复,于是就去睡觉了!");
		}

	}

	/**
	 * @value user 谈话发起方
	 * @value msg 谈话内容
	 */
	public static void say(String user, String msg) {
    
    
		System.out.println(user + " : " + msg);
	}

}

Here we look at the running results of the program:
Insert picture description here

Since we created a new thread thread to complete the task of hitting up a conversation, Chen went to sleep without waiting for the result of this task to return, and missed a good marriage. This is obviously not working, so we need to optimize the above program here to let Chen get it. thread replies to go to sleep. So how should we achieve it? This is the knowledge point join we are going to talk about today

Two, join method

1. Introduction to join Api

To learn a new method, it must be clearer to compare the official documents.
Insert picture description here
In fact, the description of the join method here can summarize only two points:

  1. After the join method is called, the current thread will wait for the target future to die before continuing to run
  2. Calling the join() method directly is equivalent to calling join(0)

Here we make a little change to the above Demo to observe the join phenomenon:

public class ChatUp {
    
    
	// 被搭讪人是否回复
	public volatile static boolean flag = false;
	// 微信昵称
	public static String userName = "土木三班陈同学";

	public static void main(String[] args) throws InterruptedException {
    
    
		// 这天陈同学闲得无聊 打开附近的人进行搭讪
		Thread thread = new Thread(() -> {
    
    
			try {
    
    

				String msg = Thread.currentThread().getName() + "同学,你好像我认识的一个人!";
				// 陈同学发起搭讪
				say(userName, msg);
				Thread.sleep(1_000);
				// 蛋蛋同学回复
				say(Thread.currentThread().getName(), "像谁?");
				flag = true;
				System.err.println(Thread.currentThread().getName()+"线程已经执行完毕");
			} catch (InterruptedException e) {
    
    
			}
		}, "蛋蛋");
		thread.start();
		thread.join();
		// 这里小小的休眠下 保证控制台输出顺序
		Thread.sleep(5l);
		// 判断是否回复了陈同学
		if (flag) {
    
    
			say(userName, "我的心上人!");
		} else {
    
    
			System.err.println("陈同学没有等到回复,于是就去睡觉了!");
		}
			System.err.println(Thread.currentThread().getName()+"线程已经执行完毕");

	}

	/**
	 * @value user 谈话发起方
	 * @value msg 谈话内容
	 */
	public static void say(String user, String msg) {
    
    
		System.out.println(user + " : " + msg);
	}
}

Observe the result:
Insert picture description here
Here we can observe that the main thread waits for the egg thread to run and gets the latest value of the flag parameter modified by the egg thread. It is proved that calling the join method allows the current thread to wait for the target thread to finish before continuing.

2. Implementation of join method

In order to figure out the implementation principle of the join method, we need to open the source code corresponding to the join:
Insert picture description here
here we are pleasantly surprised to find that the underlying implementation of the join method is actually very simple, that is, the calling thread can wait by calling the parameter form of the wait method. Of course, since he is implemented by wait, it means he also has the following characteristics:

1. Calling the wait method will immediately release the lock held by the current thread
2. When the thread is in a waiting state after calling join, calling the interrupt method will cause the current thread to throw an interruptException

3. Summary

The join method is mainly used when the current thread depends on the execution result of the target thread. It has the feature of releasing the lock immediately after the call. There is another point to note here. Many people may wonder if it calls the wait method at the bottom to achieve Pause, but no other thread was found to call the notify method to wake up. In fact, we can open the source code of the JDK on this point. There is a description in it:
Insert picture description here
when the thread ends, the thread will call the exit method to exit, the exit method calls the ensure_join method inside, and the ensure_join method calls lock. notify_all(thread) to wake up the currently waiting thread.

So far, today's content is all over, and your favorite friends can make three connections with one click!
I wish Sanlian’s friends can get a promotion and raise their salary to the pinnacle of life!

Guess you like

Origin blog.csdn.net/xiaoai1994/article/details/110817636