作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在一次使用多线程计算单词数的考试中被问到这个问题。有多种方法可以完成上述任务。生产者/消费者同步,其他不同步。我偶然发现的是使用静态变量来保持所有线程的总单词数。我想计算所有文件的总字数。我编写了这段代码,预计不会工作,因为静态变量不是线程安全的。我的问题是,如果静态变量不是线程安全的,那么为什么下面的代码可以工作。
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/
我是一名优秀的程序员,十分优秀!