1. 启动两个线程
1 public class ThreadTest { 2 3 public static boolean isRun = false; 4 5 @Test 6 public void mainTest(){ 7 System.out.println(Thread.currentThread().getName()); 8 9 Thread readThread = new ReadThread(); 10 readThread.setName("readThread"); 11 12 Thread writeThread = new WriteThread(); 13 writeThread.setName("writeThread"); 14 15 readThread.start(); 16 writeThread.start(); 17 } 18 } 19 20 class ReadThread extends Thread{ 21 @Override 22 public void run() { 23 try { 24 // 读操作比较耗时,消耗3秒的时间 25 // 由于主线程很肯能已经结束,所以,这个方法有可能不会执行到 26 sleep(3000); 27 System.out.println(Thread.currentThread().getName()); 28 } catch (InterruptedException e) { 29 e.printStackTrace(); 30 } 31 } 32 } 33 34 class WriteThread extends Thread{ 35 @Override 36 public void run() { 37 System.out.println(Thread.currentThread().getName()); 38 } 39 }
2. 由于上面的 readThread 线程比较耗时(sleep模拟),所以常常会发生主线程执行完毕,而 readThread 却没有被执行的情况,下面就想办法使得主线程等待 readThread
线程执行完毕: