0
A
回答
4
0
有一个很好的例子,使用CountDownLatch
在Javaspecialists时事通讯The Law of the Corrupt Politician。
public class TestCorruption {
private static final int THREADS = 2;
private static final CountDownLatch latch = new CountDownLatch(THREADS);
private static final BankAccount heinz = new BankAccount(1000);
public static void main(String[] args) {
for (int i = 0; i < THREADS; i++) {
addThread();
}
Timer timer = new Timer(true);
timer.schedule(new TimerTask() {
public void run() {
System.out.println(heinz.getBalance());
}
}, 100, 1000);
}
private static void addThread() {
new Thread() {
{
start();
}
public void run() {
latch.countDown();
try {
latch.await();
} catch (InterruptedException e) {
return;
}
while (true) {
heinz.deposit(100);
heinz.withdraw(100);
}
}
};
}
}
0
这取决于你的电脑有核的数量,这些将在同一时间启动线程数,这是我在这里的第一个评论,所以我希望这是正确的。
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Practica {
private static final int NUMTHREADS = 10;
public static void main(String[] args) {
CountDownLatch cdl = new CountDownLatch(NUMTHREADS);
ExecutorService executor = Executors.newFixedThreadPool(NUMTHREADS);
for (int i = 0; i < NUMTHREADS; i++) {
executor.submit(new Imp(cdl));
cdl.countDown();
System.out.println("one thread sumbmited "+cdl.getCount());
}
System.out.println("All threads submmited");
executor.shutdown();
}
}
class Imp implements Runnable {
CountDownLatch cdl;
public Imp(CountDownLatch arg) {
this.cdl = arg;
}
@Override
public void run() {
try {
cdl.await();
System.out.printf("STARTED %s at %d millis%n",
Thread.currentThread().getName(),
System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
相关问题
- 1. Java使线程同时启动
- 2. 在不同的线程中启动一个Java类
- 3. 在Java中启动不同进程中的线程
- 4. 同时启动多个线程
- 5. C++ qthread同时启动2个线程
- 6. 同时启动多个线程
- 7. 同时启动一个线程5次?
- 8. 从c中的不同线程启动一个定时器#
- 9. 同时启动和查杀线程
- 10. Java线程启动 - 停止启动在Eclipse中点击相同的按钮
- 11. 在同一个程序中启动不同的Neo4j版本
- 12. 不知道我的10个线程在启动时是否正在读取相同的.txt文件
- 13. 同时GraphicsDevice在不同的线程
- 14. 如何在同一时间启动具有不同线程功能的两个线程组?
- 15. Java:如何启动同一对象的另一个线程?
- 16. 是否所有线程都将在java并发编程中同时启动?
- 17. 在java中发生线程同步时?
- 18. C++不同的线程在FreeBSD 10上有相同的线程ID
- 19. java:不要在当前活动时启动另一个线程
- 20. 如何同时在两个不同的线程中执行PyObject_CallObject()?
- 21. 在java中同步线程
- 22. Java:在两个线程中加载相同的动态库(两个线程都在同一个JVM中)
- 23. Java多个文件不同的线程
- 24. boost :: asio在线程中启动不同的服务?
- 25. Java线程不启动
- 26. Java,线程不启动
- 27. 10使用c#在Azure表存储中同时插入10个线程
- 28. Java:线程不会同时ping通
- 29. 如何在Python中同时启动线程
- 30. java - 多个http请求同时在java中使用多线程
如果你需要它们全部在**精确**同时开始,使用'CountDownLatch'。 –
如果你需要“足够接近”,只需开始连续十次 – DeadChex
为什么所有的downvotes?这是一个完全有效的问题,需要澄清。 –