gpt4 book ai didi

java - 多线程编程和递增静态变量

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

我已阅读几乎所有与我的问题相关的帖子,但无法解决我的问题。这段代码是 Cay Horstmann 的 Big Java - Early Object 中的一个问题。该问题询问如何使用多线程编程来计算多个文件的单词数并存储组合单词数计数,这是我的问题。

为了获得组合计数器,我使用了一个static变量,该变量在线程中计数单词的每次迭代时都会递增。此外,我还使用了 ReentrantLock() 来使增量一次只能用于一个线程。除了递增之外,一切正常。有时静态变量似乎不会增加。我测试了lock()unlock()的数量由每个线程执行,它们与我的预期结果匹配,但是 static 变量无法正常工作。

有什么解释吗?感谢您的时间和帮助。

我的任务类:

 import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class WordCount implements Runnable
{
private String fileName;
Scanner inputFile;
private long counter;
public volatile static long combinedCounter = 0;
Lock ccLock;

public WordCount(String aName) throws FileNotFoundException
{
try
{
this.ccLock = new ReentrantLock();
this.counter = 0;
this.fileName = aName;
this.inputFile = new Scanner(new File(this.fileName));
}
catch (FileNotFoundException e)
{}
}
public void cCount()
{
ccLock.lock();
try
{
combinedCounter++;
/*synchronized (this)
{
combinedCounter++;
}*/
}
finally
{
ccLock.unlock();
}
}
@Override
public void run()
{
try
{
while (inputFile.hasNext() && !Thread.interrupted())
{
synchronized (this)
{
cCount();
}
counter++;
inputFile.next();
Thread.sleep(0);
}
System.out.printf("%s: %d\t\t%d\n", this.fileName,
this.counter,combinedCounter);
}
catch (InterruptedException e)
{}
}
}

这是我的客户端类:

    import java.io.FileNotFoundException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class WordCountRunner
{

public static void main(String[] args) throws FileNotFoundException,
InterruptedException
{
String a = "a.txt";
String b = "b.txt";
ExecutorService pool = Executors.newFixedThreadPool(2);
;
try
{
Runnable r1 = new WordCount(a);
Runnable r2 = new WordCount(b);
pool.execute(r1);
pool.execute(r2);

while (!pool.isTerminated())
{
pool.shutdown();
}
Thread.sleep(100);
System.out.print("***" + WordCount.combinedCounter);
}
catch (FileNotFoundException e)
{

}
finally
{
pool.shutdown();

}
}

}

最佳答案

该锁不起作用,因为 ReentrantLock 是 WordCount 类中的实例变量。因此,该类的每个实例都有自己的私有(private)锁,并且它们彼此不同步。最简单的更改是使锁静态,就像它所保护的变量一样。

关于java - 多线程编程和递增静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31597842/

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