gpt4 book ai didi

java - 与ExecutorService保持对抗?

转载 作者:行者123 更新时间:2023-12-03 13:08:35 27 4
gpt4 key购买 nike

我想保留一个已执行线程的计数器,以便在我正在执行的相同线程中使用。

这里的问题是,尽管计数器增加了,但计数器却不均匀地增加,从控制台输出中我得到了这个(我有一个用ExecutorService执行5个线程的for循环):

This is a test. N:3
This is a test. N:4
This is a test. N:4
This is a test. N:4
This is a test. N:4

如您所见,我没有得到 1,2,3,4,5,而是得到了 3,4,4,4,4

我认为这是因为for循环运行得足够快来执行线程,并且线程足够快来执行请求计数器的代码的速度快于计数器自身的更新速度(这是否有意义?)。

这是代码(它更小,并且没有用于计数器的有意义的代码):
for (int i = 0; i  <  5; i++)
{

Thread thread;
thread = new Thread()
{

public void run()
{



System.out.println("This is test. N: "+aldo );
//In here there is much more stuff, saying it because it might slow down the execution (if that is the culprit?)
return;
}
};

threadList.add(thread);
}
//later
for (int i = 0; i < threadList.size(); i++)
{

executor.execute(threadList.get(i));
aldo = aldo + 1;

}
executor.shutdown();
try
{
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
}
catch (InterruptedException e)
{

}

是的, aldo计数器(我认为还有一些其他列表)在代码中丢失了(它们非常简单)。

最佳答案

我所知道的最好方法是通过使用传入数字的构造函数创建自定义线程类。包含数字的变量随后可用于以后任何所需的日志记录。这是我想出的代码。

public static void main(String[] args) {
class NumberedThread implements Runnable {
private final int number;
public NumberedThread(int number) {
this.number = number;
}

@Override
public void run() {
System.out.println("This is test. N: " + number);
}
}

List<Thread> threadList = new ArrayList<>();
for (int i = 1; i < 6; i++) threadList.add(new Thread(new NumberedThread(i)));

ExecutorService executor = Executors.newFixedThreadPool(10);;
for (Thread thread : threadList) executor.execute(thread);
executor.shutdown();
try {
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
}
catch (InterruptedException ignored) { }
}

如果要命名线程,也可以使用字符串对象。

关于java - 与ExecutorService保持对抗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48551291/

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