gpt4 book ai didi

java - 捕获并行线程的总执行时间

转载 作者:行者123 更新时间:2023-12-01 12:59:25 25 4
gpt4 key购买 nike

我正在使用 java.util.concurrent.Executors 和 java.util.concurrent.ExecutorService 来执行并行线程。请让我知道如何捕获完成所有线程所花费的时间。

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CallBackTest {
private static int NUM_OF_TASKS = 50;
Object result;
int cnt = 0;
long begTest, endTest;

public CallBackTest() { }

public void callBack(Object result) {
System.out.println("result "+result);
this.result = result;
}


public void run() {

ExecutorService es = Executors.newFixedThreadPool(50);
for(int i = 0; i < NUM_OF_TASKS; i++) {

CallBackTask task = new CallBackTask(i);
task.setCaller(this);
es.submit(task);
// at this point after submitting the tasks the
// main thread is free to perform other work.
}
}

public static void main(String[] args) {
new CallBackTest().run();
}
}

最佳答案

创建简单任务为

public class SimpleTask implements Runnable {
AtomicLong totalTime;
public SimpleTask(AtomicLong totalTime) {
this.totalTime = totalTime;
}
@Override
public void run() {
long currentTime = System.nanoTime();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
totalTime.addAndGet(System.nanoTime()-currentTime);
}
}

//Main 将 AtomicLong 传递给每个任务以捕获该线程所花费的时间。并将其求和到同一个实例。 AtomicLong 是线程安全的。

           AtomicLong totalTime = new AtomicLong(0);
long currentTime = System.nanoTime();
ExecutorService executor = Executors.newFixedThreadPool(numberofThread);
for (int i = 0; i < numberofTasks; i++) {
SimpleTask task = new SimpleTask(totalTime);
executor.submit(task);
}
executor.shutdown();

//等待所有线程完成。

try {
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {}

//计算时间

System.out.println("Overall time"+ (System.nanoTime()-currentTime));

//从 Atomic Long 中获取值

    System.out.println("All Threads Spent time"+ totalTime);

关于java - 捕获并行线程的总执行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23640858/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com