赞
踩
可以使用join()方法(但中间加了Thread.sleep(1000)以后就不按顺序执行,不知道为什么)
public static void main(String[] args) throws CloneNotSupportedException { // 创建线程对象 Thread t1 = new Thread(() -> { System.out.println("t1"); }); Thread t2 = new Thread(() -> { try { t1.join(); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println("t2"); }); Thread t3 = new Thread(() -> { try { t2.join(); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println("t3"); }); // 启动线程,启动顺序无所谓,因为有join的约束 t3.start(); t2.start(); t1.start(); }
public static void main(String[] args) throws CloneNotSupportedException, InterruptedException { Object LOCK = new Object(); Thread t1 = new Thread(() -> { System.out.println("t1"); synchronized (LOCK) { LOCK.notify(); } }); Thread t2 = new Thread(() -> { try { synchronized (LOCK) { LOCK.wait(); } } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println("t2"); }); t2.start(); Thread.sleep(1000); t1.start(); }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。