我想比较solaris / linux / windows 64位JVM的线程性能,以及下面的代码。
我个人更喜欢这种编码方式的线程,因为你有一个方法执行一些计算,你想在不同的线程上运行该计算。我使用Thread类启动对象看起来并不直观。因此,请在同一行(如果需要)上建议我使用备用代码样式。
public class Dummy2 {
private static int NUM_OF_THREADS=100000;
public void loopSomeTime() {
Thread t = new Thread(new Runnable(){
public void run(){
int count = 0;
for(int i = 0; i < 1000000; ++i){
count++;
}
System.out.println(count);
}
});
t.start();
}
public static void main(String[] args){
long beginTime = System.nanoTime();
for(int i =0; i < NUM_OF_THREADS ; i++){
Dummy2 d = new Dummy2();
d.loopSomeTime();
}
//I need to wait here
long endTime = System.nanoTime() - beginTime;
System.out.println(endTime/(1000*1000) + "milliseconds");
}
}
如何在MainThread中计算endTime
之前等待所有线程完成?
注意:我是java初学者和学习Java线程
答案 0 :(得分:2)
这里的关键是你需要一些方法来等待所有的线程完成。但是,线程是低级构造,很难正确管理。
使用更高级别的构造,您可以将一些棘手的脏工作推送到Java框架中,并专注于您要执行的操作:等待线程完成。
这是一些Java,它说明了我推荐的整体设计。它不完整,但应该是一个良好的开端。
public static void main(String[] args) {
final int threads = 1000;
ExecutorService exec = Executors.newFixedThreadPool(threads);
List<Future<?>> futures = new LinkedList<>();
final long start = System.currentTimeMillis();
for (int i = 0; i < threads; ++i) {
futures.add(exec.submit(makeTask()));
}
while (!futures.isEmpty()) {
Iterator<Future<?>> it = futures.iterator();
while (it.hasNext()) {
if (it.next().isDone()) {
it.remove();
}
}
}
final long duration = System.currentTimeMillis() - start;
// TODO: report the difference.
}
private static Runnable makeTask() {
// TODO: return a Runnable that does stuff.
return null;
}
答案 1 :(得分:1)
您需要跟踪所有线程并在每个线程上调用join
。
public class Test {
private static int NUM_OF_THREADS = 100000;
// Keep track of my thread.
private Thread thread;
public void loopSomeTime() {
thread = new Thread(new Runnable() {
public void run() {
int count = 0;
for (int i = 0; i < 1000000; ++i) {
count++;
}
System.out.println(count);
}
});
thread.start();
}
public void waitToFinish() throws InterruptedException {
thread.join();
}
public static void main(String[] args) throws InterruptedException {
List<Test> loopers = new ArrayList<>();
long beginTime = System.nanoTime();
for (int i = 0; i < NUM_OF_THREADS; i++) {
Test d = new Test();
d.loopSomeTime();
// Keep track of all loopers.
loopers.add(d);
}
//I need to wait here
for (Test t : loopers) {
t.waitToFinish();
}
long endTime = System.nanoTime() - beginTime;
System.out.println(endTime / (1000 * 1000) + "milliseconds");
}
}