【发布时间】:2014-12-06 10:46:24
【问题描述】:
我正在尝试找出线程创建和同步所需的时间。我知道我应该使用 ThreadMXBean,但是我找不到使用 ThreadMXBean 和 Callable 接口演示这一点的简单示例。
package teststckofw;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class TestStckOfw {
public static void main(String[] args) throws ExecutionException {
int i = 0;
int processed = 0;
while (i < 10) {
Parallel parallel1 = new Parallel();
Parallel parallel2 = new Parallel();
ExecutorService exec1 = Executors.newCachedThreadPool();
List<Callable<Integer>> tasks1 = new ArrayList<>();
try {
tasks1.add(parallel1);
tasks1.add(parallel2);
try {
List<Future<Integer>> futures = exec1.invokeAll(tasks1);
int flag = 0;
for (Future<Integer> f : futures) {
Integer res = f.get();
if (res != 0) {
processed = res;
}
if (!f.isDone()) {
flag = 1;
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} finally {
exec1.shutdown();
}
i++;
}
}
/**************************************/
static class Parallel implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int a = 2 + 2; // do something...
return a;
}
}
}
编辑: 我需要在长时间循环期间所有线程的信息,其中包含许多迭代(远远超过 10 次)。我可以使用线程转储获取所有迭代中所有线程的摘要信息吗?
【问题讨论】:
标签: java multithreading synchronization creation callable