public class JoinTest { public static void main(String[] args) { // TODO Auto-generated method stub Thread t1 = new ThreadA();//利用多态实例化一个A线程 Thread t2 = new ThreadB(t1);//利用多态实例化一个B线程 t1.start(); t2.start(); } } /*继承于Thread的子类*/ class ThreadA extends Thread { public void run() { for (int i = 1; i <= 20; i++) { System.out.println(i + " ¥¥¥"); try { Thread.sleep(1000); } catch (InterruptedException e) { } } } } /*继承于Thread的子类*/ class ThreadB extends Thread { private Thread t; public ThreadB() { } public ThreadB(Thread t) { this.t = t; } public void run() { for (int i = 1; i <= 20; i++) { System.out.println(i + " ###"); try { Thread.sleep(1000); if (i == 10) { t.join();// join 使这两个线程进入串行状态(也就是说t突然插了进来,必须等t执行完毕之后,才会让B线程继续执行) } } catch (InterruptedException e) { } } } }
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/11070.html