要檢查我已經寫的代碼主題:如何檢查池「重用」主題
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>
它的用法是正確的只有螺紋不變。至少在測試中。
據我所知equals/hashCode沒有被覆蓋,因此從Object繼承。
因此,請回答如果我的測試不正確,哪裏出錯。
如果你知道更聰明的方式,請分享一下。
你能解釋進一步你遇到什麼問題?你的代碼在我的項目中運行良好。 – Henrik
@Henrik我不確定我是否正確地調整了線程輪詢「重用」線程的方式 – gstackoverflow
我會爭辯說,您的代碼實際上設法驗證test()是使用它們創建100個線程並執行500個小任務。如果情況不是這樣,你的'RunTimeException'將被拋出。你正在尋找更短的方式來證明這一點? – Henrik