【发布时间】:2017-02-16 13:36:38
【问题描述】:
为了检查我写了代码的主题:
public class ThreadPoolTest {
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 100; i++) {
if (test() != 5 * 100) {
throw new RuntimeException("main");
}
}
test();
}
private static long test() throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(100);
CountDownLatch countDownLatch = new CountDownLatch(100 * 5);
Set<Thread> threads = Collections.synchronizedSet(new HashSet<>());
AtomicLong atomicLong = new AtomicLong();
for (int i = 0; i < 5 * 100; i++) {
executorService.submit(new Runnable() {
@Override
public void run() {
try {
threads.add(Thread.currentThread());
atomicLong.incrementAndGet();
countDownLatch.countDown();
} catch (Exception e) {
System.out.println(e);
}
}
});
}
executorService.shutdown();
countDownLatch.await();
if (threads.size() != 100) {
throw new RuntimeException("test");
}
return atomicLong.get();
}
}
如你所见,我使用HashSet<Thread>
只有当 Thread 不可变时,它的使用才是正确的。至少在测试中。
据我了解,equals/hashCode 未被覆盖,因此从 Object 继承。
因此,如果我的测试不正确以及错误在哪里,请回答。
如果您知道更聪明的方法,请分享。
【问题讨论】:
-
您能进一步解释您遇到的问题吗?您的代码在我的项目中运行良好。
-
@Henrik 我不确定我是否理解线程轮询如何“重用”线程
-
我认为您的代码实际上设法验证
test()创建了 100 个线程并使用它们执行了 500 个小任务。如果不是这种情况,您的RunTimeExceptions 将被抛出。您是否正在寻找更短的方法来证明这一点? -
@Henrik 讨厌这个实验很长时间,我确信这个输出保证了
标签: java multithreading threadpool