ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
Thread类的join方法用来使main线程进入阻塞状态,进而等待调用join方法的线程执行,join方法有如下三种形式 ~~~ public final void join(long millis) throws InterruptedException public final void join(long millis, int nanos) throws InterruptedException public final void join() throws InterruptedException ~~~ 带参数的join方法,表示至多等待线程A的时间,而无参数的join方法,则会一直等待线程A执行结束。通过下例来说明。首先我们看不加join方法的版本,两个线程并行执行,在run方法中睡眠15秒后同时结束: ~~~ public static void main(String[] args) { System.out.println("Main Thread Start..."+new Date()); CreateThreadTest ctt = new CreateThreadTest(); Thread t1 = new Thread(ctt,"t1"); Thread t2 = new Thread(ctt,"t2"); t1.start(); t2.start(); } public class CreateThreadTest implements Runnable { @Override public void run() { System.out.println("线程"+Thread.currentThread().getName()+":开始运行"+new Date()); try{ Thread.sleep(15000); //doDBProcessing(); }catch(InterruptedException e){ e.printStackTrace(); } System.out.println("线程"+Thread.currentThread().getName()+":结束运行"+new Date()); } } ~~~ 结果: ~~~ Main Thread Start...Thu Jul 06 14:48:37 CST 2017 线程t1:开始运行Thu Jul 06 14:48:38 CST 2017 线程t2:开始运行Thu Jul 06 14:48:38 CST 2017 线程t2:结束运行Thu Jul 06 14:48:53 CST 2017 线程t1:结束运行Thu Jul 06 14:48:53 CST 2017 ~~~ 如果加入join()方法呢: ~~~ public static void main(String[] args) { System.out.println("Main Thread Start..."+new Date()); CreateThreadTest ctt = new CreateThreadTest(); Thread t1 = new Thread(ctt,"t1"); Thread t2 = new Thread(ctt,"t2"); try{ t1.start(); t1.join(); t2.start(); }catch(Exception e){ e.printStackTrace(); } } ~~~ 原本并行的两个线程变为了串行执行,也就是说,父线程会等待子线程的执行完毕: ~~~ Main Thread Start...Thu Jul 06 14:53:34 CST 2017 线程t1:开始运行Thu Jul 06 14:53:34 CST 2017 线程t1:结束运行Thu Jul 06 14:53:49 CST 2017 线程t2:开始运行Thu Jul 06 14:53:49 CST 2017 线程t2:结束运行Thu Jul 06 14:54:04 CST 2017 ~~~