🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
-欢迎关注我的公众号: ![我的公众号](https://markdown-1258186581.cos.ap-shanghai.myqcloud.com/20190606104746.png) # 给定三个线程如何顺序执行完以后在主线程拿到执行结果 这里采用线程的 join 方法实现,在一个线程 A 内部如果调用另外一个线程 B 的 join 方法,那么线程 A 就会等待 B 执行完以后再执行。 定义线程 Thread11: ```java class Thread11 implements Runnable { private String name; private Thread thread; public Thread11(String name) { this.name = name; } public Thread getThread() { return thread; } public void setThread(Thread thread) { this.thread = thread; } @Override public void run() { System.out.println(name+ "线程运行开始!"); try { if (thread!=null) thread.join(); Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } finally { System.out.println(name + "线程运行结束!"); } } } ``` 创建三个线程: ```java Thread11 thread1 = new Thread11("线程A"); Thread11 thread2 = new Thread11("线程B"); Thread11 thread3 = new Thread11("线程C"); Thread threadA = new Thread(thread1); Thread threadB = new Thread(thread2); Thread threadC = new Thread(thread3); ``` 这里创建A、B、C三个线程,下面的操作是让线程按照 A -> B -> C -> 主线程的顺序执行: ```java public static void main(String[] args) { System.out.println(Thread.currentThread().getName() + "线程运行开始!"); Thread11 thread1 = new Thread11("线程A"); Thread11 thread2 = new Thread11("线程B"); Thread11 thread3 = new Thread11("线程C"); Thread threadA = new Thread(thread1); Thread threadB = new Thread(thread2); Thread threadC = new Thread(thread3); thread2.setThread(threadA); thread3.setThread(threadB); threadA.start(); threadB.start(); threadC.start(); try { threadC.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "线程运行结束!"); } ``` 运行结果: ![](https://markdown-1258186581.cos.ap-shanghai.myqcloud.com/20200229002657.png)