gpt4 book ai didi

java - 执行器服务不一致

转载 作者:行者123 更新时间:2023-12-03 12:53:54 26 4
gpt4 key购买 nike

我正在测试HashIds的碰撞。这里是依赖项:

    <!-- https://mvnrepository.com/artifact/org.hashids/hashids -->
<dependency>
<groupId>org.hashids</groupId>
<artifactId>hashids</artifactId>
<version>1.0.3</version>
</dependency>
我正在使用以下代码:
    Hashids hashids = new Hashids("xyz", 6, "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ");

System.out.println("*******************************************************************");
System.out.println("Started");

Set<String> set = new HashSet();

ExecutorService executor = Executors.newFixedThreadPool(4);

AtomicLong count = new AtomicLong(0);
final long max = 10_000_000;
for (long i = 1; i <= max; i++) {

executor.execute(() -> {
set.add(hashids.encode(count.incrementAndGet()));

// This is just to show me that there is some activity going on
if (count.get() % 100_000 == 0) {
System.out.println(count.get() + ": " + new Date());
}
});
}

// Wait till the executor service tasks are done
executor.shutdown();
while (!executor.isTerminated()) {
Thread.sleep(1000);
}

// Assert that the Set did not receive duplicates
Assert.assertEquals(max, set.size());

System.out.println("Ended");
System.out.println("*******************************************************************");
所以,我放了一个 ExecutorService使其更快一些,但是我遇到了问题。任何一个
  • ExecutorService未完成,并且卡在那里
  • Set包含重复值,因此断言失败
  • 使用裸for循环比使用ExecutorService
  • 快得多

    这段代码可能有什么问题?

    最佳答案

  • 您需要在executor.shutdown() ;之后立即调用executor.awaitTermination
  • 您的Set不是线程安全的,请尝试使用Collections.synchronizedSet(set)包装您的集合,或基于ConcurrentHashMap.newKeySet()创建集合,请参阅有关thread safe set的讨论。
  • 关于java - 执行器服务不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62548215/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com