如何在Java中的Y线程上运行X任务?

Kam*_*mil 4 java multithreading executorservice multitasking threadpoolexecutor

我想确保在执行100个任务的5个线程上执行任务的平均时间.

为了节省时间,我使用了 nanoTime()

任务是调用一个特定的方法,让我们调用它foo(); 我不创建任何其他类.

在我的代码中,我创建了一个任务:

Runnable thExecute = new Runnable(){
  @Override
  public void run(){
    foo();
  }
};
Run Code Online (Sandbox Code Playgroud)

然后我创建一个线程:

Thread th = new Thread(thExecute);
long start = System.nanoTime();
th.run();
long stop = System.nanoTime();
Run Code Online (Sandbox Code Playgroud)

如果我有与线程相同数量的任务,这将是很好的.我试图创建线程和任务的数组:

Runnable[] thExecutes = new Runnable[100];
Thread[] ths = new Thread[5];
Run Code Online (Sandbox Code Playgroud)

但现在我不知道接下来该做什么.我知道他们应该以某种方式排队,可能我应该Executor上课.我使用Java 6.

编辑:起初我并不是说我写的东西.现在我知道我想要平均时间+最长时间.

Ada*_*ker 5

首先要注意的是:如果您自己测量性能,则不应该期望精确的结果.有一些工具可以帮到您,提供更可靠的结果.

如果您想自己动手,请使用ExecutorService:

ExecutorService service = Executors.newFixedThreadPool(5);
long startTs = System.nanoTime();

List<Future> futures = new ArrayList<>();
for (Runnable r : runnables) {
    futures.add(service.submit(r));
}
for (Future f : futures) { 
    f.get(); 
}

long durationNs = System.nanoTime() - startTs;
Run Code Online (Sandbox Code Playgroud)

再说一遍:由于你测量纳秒,我强烈建议你避免手动测量,因为有许多因素会破坏结果:没有预热,设置费用等.

更新:要测量每个任务的执行时间,您可以提交Callable<Long>而不是Runnable

public long call() {
    long startTs = System.nanoTime();
    // do the task
    return System.nanoTime() - startTs;
}
Run Code Online (Sandbox Code Playgroud)

现在Future将返回执行时间,您可以打印它或收集列表:

for (Future<Long> f : futures) {
    long spentTime = f.get();
}
Run Code Online (Sandbox Code Playgroud)