1
我想了解線程創建和同步所需的時間。我知道我應該使用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)的很長一段時間循環中需要的所有線程的信息。我可以通過使用線程轉儲獲得所有迭代中所有線程的摘要信息嗎?