我正在尝试计算我的程序创建的所有线程,但我的代码只计算调用时间。
我确信因为在输出中我看到在所有线程完成之前打印的差异
下面是我的主程序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
我尝试使用加入,但对我不起作用
答案 0 :(得分:1)
您可以使用CountDownLatch
等待一定数量的线程调用countDown()
,然后您可以打印运行时间。您需要更改Customer
类以获取CountDownLatch
对象,以便可以正确调用countDown()
方法,但一旦这样做,这应该可以。
类似的东西:
CountDownLatch latch = new CountDownLatch(customers.size());
long startTimestamp = System.currentTimeMillis();
for (Customer c: customers){
new RequestProcessor(c, i++, latch).start();
}
latch.await();
// have each thread call countDown() after it's done, etc.
你可能需要做一些更复杂的事情,比如有两个锁存器,这样你就可以通过让一个锁存器阻塞每个创建的线程来获得更好的时间,直到你在主线程中调用countDown()
,但这就是一般的想法。
答案 1 :(得分:1)
您可以使用CountDownLatch。它是一个重要的并发工具类。 如果你想了解更多关于java多线程程序的信息。请参阅 Java Concurrency in Practice [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
}