主要作用是同步,它可以使得线程之间的并行执行变为串行执行。在A线程中调用了B线程的join()方法时,表示只有当B线程
执行完毕时,A线程才能继续执行。
/** * join方法的使用 */ public class UseJoin { private static class JumpQueue implements Runnable { private Thread thread; // 用来插队的线程 public JumpQueue(Thread thread) { this.thread = thread; } public void run() { try { thread.join(); System.out.println(Thread.currentThread().getName()+" is running!"); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) throws Exception { Thread previous = Thread.currentThread();//现在是主线程 for (int i = 0; i < 3; i++) { Thread thread = new Thread(new JumpQueue(previous), "线程" + i); System.out.println(previous.getName() + " inserts in front of " + thread.getName()); thread.start(); previous = thread; } System.out.println(Thread.currentThread().getName() + " end!"); } }