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

时间:2014-05-13 20:20:48

标签: java multithreading concurrency parallel-processing

我使用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();
           }
    }

1 个答案:

答案 0 :(得分:0)

创建简单任务

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 Pass 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);