栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java 如何同时启动两个线程

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java 如何同时启动两个线程

要完全同时(至少尽可能好)启动线程,可以使用CyclicBarrier:

// We want to start just 2 threads at the same time, but let's control that // timing from the main thread. That's why we have 3 "parties" instead of 2.final CyclicBarrier gate = new CyclicBarrier(3);Thread t1 = new Thread(){    public void run(){        gate.await();        //do stuff        }};Thread t2 = new Thread(){    public void run(){        gate.await();        //do stuff        }};t1.start();t2.start();// At this point, t1 and t2 are blocking on the gate. // Since we gave "3" as the argument, gate is not opened yet.// Now if we block on the gate from the main thread, it will open// and all threads will start to do stuff!gate.await();System.out.println("all threads started");

这不必是

CyclicBarrier
,你也可以使用
CountDownLatch

这仍然无法确保它们已正确启动

在其他平台上,确切地说启动线程可能是非常有效的要求。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/456644.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号