Java中join()方法的重要性?
一个连接()是最后 的方法线程 类,它可用于线程的执行开始加盟另一个线程的执行结束,这样直到另一个线程结束线程将无法启动运行。如果在线程实例上调用join()方法,则当前正在运行的线程将阻塞,直到线程实例执行完毕。
语法
public final void join() throws InterruptedException
示例
public class JoinTest extends Thread { public void run() { for(int i=1; i <= 3; i++) { try { Thread.sleep(1000); } catch(Exception e) { System.out.println(e); } System.out.println("nhooo "+ i); } } public static void main(String args[]) { JoinTest t1 = new JoinTest(); JoinTest t2 = new JoinTest(); JoinTest t3 = new JoinTest(); t1.start(); try { t1.join(); // calling join() method } catch(Exception e) { System.out.println(e); } t2.start(); t3.start(); } }
输出结果
nhooo 1 nhooo 2 nhooo 3 nhooo 1 nhooo 1 nhooo 2 nhooo 2 nhooo 3 nhooo 3