Thread expansion (join usage)

Let's look at a picture together:

How to give up the execution right of the current thread

The yield() method, which can only be seen in some internal implementations of the JDK, is to give up execution rights and is basically not used. After giving up, it becomes operational.

join method

The t.join() method will only make the main thread (or the thread that calls t.join()) enter the waiting pool and wait for the t thread to finish executing before it will be awakened. It does not affect other threads that are running at the same time.

analysis:

package CSDN;
public class TestJoin {
 
	public static void main(String[] args) throws InterruptedException {
		// TODO Auto-generated method stub
		ThreadTest t1=new ThreadTest("A");
		ThreadTest t2=new ThreadTest("B");
		t1.start();
		t2.start();
	}
 
 
}
class ThreadTest extends Thread {
	private String name;
	public ThreadTest(String name){
		this.name=name;
	}
	public void run(){
		for(int i=1;i<=5;i++){
				System.out.println(name+"-"+i);
		}		
	}
}

Print result:

  1. A-1

  2. B-1

  3. B-2

  4. B-3

  5. A-2

  6. B-4

  7. A-3

  8. B-5

  9. A-4

  10. A-5

You can see that the two threads are executed alternately.

When we join the join:

package CSDN;
public class TestJoin {
 
	public static void main(String[] args) throws InterruptedException {
		// TODO Auto-generated method stub
		ThreadTest t1=new ThreadTest("A");
		ThreadTest t2=new ThreadTest("B");
		t1.start();
		t1.join();
		t2.start();
	}
}

Print result:


A-1
A-2
A-3
A-4
A-5
B-1
B-2
B-3
B-4
B-5

 

Guess you like

Origin blog.csdn.net/qq_36428821/article/details/113443085