gpt4 book ai didi

java - static int 变量线程安全吗?

转载 作者:行者123 更新时间:2023-11-30 03:55:24 25 4
gpt4 key购买 nike

我在一次使用多线程计算单词数的考试中被问到这个问题。有多种方法可以完成上述任务。生产者/消费者同步,其他不同步。我偶然发现的是使用静态变量来保持所有线程的总单词数。我想计算所有文件的总字数。我编写了这段代码,预计不会工作,因为静态变量不是线程安全的。我的问题是,如果静态变量不是线程安全的,那么为什么下面的代码可以工作。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class WordCount implements Runnable {

String fileName;
static int totalCount = 0;
static int numThreads = 0;

public WordCount(String[] files) {

for (String file : files) {

new Thread(this, file).start();
}

}

public void run() {

int count = 0;
try {
Scanner in = new Scanner(new File(Thread.currentThread().getName()));

while (in.hasNext()) {
in.next();
count++;
}

System.out.println(Thread.currentThread().getName() + ": " + count);
totalCount += count;
numThreads++;
totalCount();
} catch (FileNotFoundException e) {
System.out.println(Thread.currentThread().getName() + ": Not Found");
}

}

public void totalCount() {

if (numThreads == 3) {
System.out.println("total: " + totalCount);
}
}

public int getTotalWords() {

return totalCount;
}
}

最佳答案

非线程安全并不意味着永远无法工作。这意味着并不总是按预期工作。在您的示例中,您可以更改 numThreads 或totalCount,但在打印这些变量之前,这些变量将由另一个线程更新。您应该避免在线程之间共享非最终变量,如果不能,您应该使用 synchronized强制线程排队以使用变量。但是,同步并不是万能药,因此您仍然需要注意自己在做什么以及为什么这样做。

关于java - static int 变量线程安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23347566/

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