gpt4 book ai didi

java - 计算文本中的逗号(多线程),我做得对吗?

转载 作者:行者123 更新时间:2023-12-01 18:02:19 25 4
gpt4 key购买 nike

我使用 5 个线程来计算文本中的逗号,方法是将文本分成 5 个相等的部分,并让每个线程处理自己的部分。我只是想知道我做得是否正确:

public class CommaCounter implements Runnable {

public static int commaCount = 0; // it's static so that all CommaCounter threads share the same variable

private String text;
private int startIndex;
private int endIndex;

public CommaCounter(String text, int startIndex, int endIndex) {
this.text = text;
this.startIndex = startIndex;
this.endIndex = endIndex;
}

@Override
public void run() {

for (int i = startIndex; i < endIndex; i++) {
if(text.charAt(i) == ','){
commaCount++; // is incrementing OKAY? is there danger of thread interference or memory consistency errors?
}
}
}
}

主要方法:

public class Demo {

public static void main(String[] args) throws MalformedURLException, IOException, InterruptedException {

long startTime = System.currentTimeMillis();
/*
I'll spare the code that was here for retrieving the text from a URL
*/

String text = stringBuilder.toString();

Set<Thread> threadCollection = new HashSet<>();

int threadCount = 5;
int textPerThread = text.length() / threadCount;
for (int i = 0; i < threadCount; i++) {
int start = i * textPerThread;
Thread t = new Thread(new CommaCounter(text, start, start + textPerThread));
threadCollection.add(t);
t.start();
}

for (Thread thread : threadCollection) {
thread.join(); // joining each CommaCounter thread, so that the code after the for loop doesn't execute prematurely
}

long endTime = System.currentTimeMillis();
System.out.println("Counting the commas with " + threadCount + " threads took: " + (endTime - startTime) + "ms");
System.out.println("Comma count: " + CommaCounter.commaCount);
}

}

主要是我担心递增 commaCount 是否正确完成,即是否存在线程干扰或内存一致性错误的危险。我也很好奇为什么执行时间并不比用单个线程计算逗号时要好得多(几乎相同)。

如有任何帮助,我们将不胜感激!

最佳答案

绝对不行。您正在从多个线程访问静态变量。使用 AtomicInteger 或同步静态方法。

正如您的评论中所述,完全正确:)

将其设置为 AtomicInteger 并使用 getAndIncrement 或incrementAndGet 方法,

或者创建一个静态同步方法,

或者创建一个同步块(synchronized block),但在这种情况下,请确保同步的对象是相同的!由于这是关于类 CommaCounter 中的静态变量,因此可能是 CommaCounter.class

关于java - 计算文本中的逗号(多线程),我做得对吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39941791/

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