java 线程中的 join
package thread; import java.util.Arrays; import java.util.Random; public class Thread_join { public static void main(String[] args) { /** * 2个线程共享同一个数组,t1负责向数组中添加100个随机数, * t2负责排序,其中t2要等待t1的结束再继续排序 * * @author 清风已来 * */ int[] arr = new int[100]; Thread t1 = new ThreadA(arr); Thread t2 = new ThreadB(arr,t1); t1.start(); t2.start(); } } // 负责生成100个随机数 class ThreadA extends Thread { int[] arr; public ThreadA(int[] arr) { this.arr = arr; } public void run() { Random random = new Random(); for (int i = 0; i < arr.length; i++) { arr[i] = random.nextInt(100); } // 输出数组中全部的数据 System.out.println(Arrays.toString(arr)); } } // 负责对100个数进行排序 class ThreadB extends Thread { int[] arr; Thread t1; public ThreadB(int[] arr,Thread t1) { this.arr = arr; this.t1 = t1; } public void run() { try { System.out.println("等待t1的结束!"); // 等待t1的结束 t1.join(); //t1已经正常结束,可以进行排序了 Arrays.sort(arr); System.out.println(Arrays.toString(arr)); } catch (InterruptedException e) { //等待t1结束期间,被其他线程打断,提前结束等待 e.printStackTrace(); } } }