我有10个不同的主题,我想同时开始。同时,我的意思不是按顺序启动它们(尽管这将会很接近)。
在java中实现这一目标的最佳方法是什么?
答案 0 :(得分:4)
准确:您将无法在同一时间启动所有10个线程。 ms或ns的顺序会有所不同。你可以尽量减少这种差异。即便如此:如果你的内核少于线程,那么前几个线程在其他线程执行第一条指令之前就会完成一些工作。
答案 1 :(得分:0)
在Javaspecialists简报The Law of the Corrupt Politician中有一个使用CountDownLatch
的好例子。
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);
}
}
};
}
}
答案 2 :(得分: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();
}
}
}