gpt4 book ai didi

java - 如何计算我的多线程程序的运行时间

转载 作者:行者123 更新时间:2023-11-30 03:54:11 45 4
gpt4 key购买 nike

我正在尝试计算我的程序创建的所有线程的总数,但我的代码仅计算调用的时间。

我确信,因为在输出中我看到在所有线程完成之前打印的差异

下面是我的主程序RequestProcessor这里是我的线程类

int i = 0;
List<Customer>customers = customer.getCustomers();
long startTimestamp = System.currentTimeMillis();
for (Customer c: customers){
new RequestProcessor(c, i).start();
i++;
}
long endTimestamp = System.currentTimeMillis();
System.out.println("difference = "+(endTimestamp - startTimestamp));

下面是请求处理器类

public RequestProcessor( Customer customer , int threadSeq ) {
super();
this.customer = customer;
this.threadSeq = threadSeq;
}

@Override
public void run() {
// TODO Auto-generated method stub
processRequest();
super.run();
}

public void processRequest(){
//performing execution on customer here
System.out.println("processing "+ customer.getName()+" thread seq "+threadSeq);
}

下面是我得到的输出

processing customer9 thread seq 9
processing customer7 thread seq 7
difference = 4
processing customer3 thread seq 3
processing customer2 thread seq 2

我尝试使用 join 但对我不起作用

最佳答案

您可以使用CountDownLatch 。它是一个重要的并发工具类。如果您想了解更多有关java多线程程序的信息。请参阅实践中的 Java 并发 [Brian Goetz]

这本书
 int i = 0;
List<Customer>customers = customer.getCustomers();
CountDownLatch cdl =new CountDownLatch(customers.size()); // new code
long startTimestamp = System.currentTimeMillis();

for (Customer c: customers){
new RequestProcessor(cdl,c, i).start();
i++;
}

cdl.await(); // new code .
// the thread will hang up unitl all RequestProcessor run cdl.countDown() ;
long endTimestamp = System.currentTimeMillis();
System.out.println("difference = "+(endTimestamp - startTimestamp));

RequestProcessor.class

public RequestProcessor(CountDownLatch cdl, Customer customer , int threadSeq ) {
super();
this.customer = customer;
this.threadSeq = threadSeq;
this.cdl=cdl; // new code
}
@Override
public void run() {
// TODO Auto-generated method stub
processRequest();
super.run();
cdl.countDown(); // new code
}

关于java - 如何计算我的多线程程序的运行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23673406/

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