1. A. join: the explanation in the API is that the current thread B is blocked until the execution of A is complete and dead, and then B is executed.
Let's illustrate it with a small example.
static class ThreadA extends Thread {@Overridepublic void run() {// TODO Auto-generated method stubsuper.run();for (int i = 0; i < 10; i++) {System.out.println(ThreadA + i);}}}static class ThreadB extends Thread {ThreadA a;public ThreadB(ThreadA a) {// TODO Auto-generated constructor stubthis.a = a;}@Overridepublic void run() {// TODO Auto-generated method stubsuper.run();System.out.println(ThreadB start);try {a.join();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println(ThreadB end);}}public static void main(String[] args) {ThreadA a = new ThreadA();ThreadB b = new ThreadB(a);b.start();a.start();}
Execution result:
ThreadB startThreadA0ThreadA1ThreadA2ThreadA3ThreadA4ThreadA5ThreadA6ThreadA7ThreadA8ThreadA9ThreadB end
First, thread B executes the statement. After thread a joins, thread a executes a directly before thread B executes the statement.
2. Execute A. yield, A to B, and B to end A and then execute. This is the opposite of join!
static class ThreadA extends Thread {@Overridepublic void run() {// TODO Auto-generated method stubsuper.run();for (int i = 0; i < 10; i++) {System.out.println(ThreadA + i);}}}static class ThreadB extends Thread {ThreadA a;public ThreadB(ThreadA a) {// TODO Auto-generated constructor stubthis.a = a;}@Overridepublic void run() {// TODO Auto-generated method stubsuper.run();System.out.println(ThreadB start);try {for (int i = 0; i < 10; i++) {if(i==2){a.yield();}System.out.println(ThreadB + i);}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println(ThreadB end);}}public static void main(String[] args) {ThreadA a = new ThreadA();ThreadB b = new ThreadB(a);b.start();a.start();}
Execution result:
ThreadB startThreadA 0ThreadB 0ThreadA 1ThreadB 1ThreadA 2ThreadB 2ThreadB 3ThreadB 4ThreadB 5ThreadB 6ThreadB 7ThreadB 8ThreadB 9ThreadB endThreadA 3ThreadA 4ThreadA 5ThreadA 6ThreadA 7ThreadA 8ThreadA 9
First, execute B, and then execute A. in the loop of B, when I = 2, A executes yield. Then, after B completes execution, it is the turn of A to execute.