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

标签 java multithreading static locking

我已阅读几乎所有与我的问题相关的帖子,但无法解决我的问题。这段代码是 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/

相关文章:

java - 打开连接时出错 java.io.IOException : Server returned HTTP response code: 501 for URL

java - Apache Commons Lang3 与 Apache Commons Text 之间有什么区别?

java - Spring MVC : Threads not executing in production

java - 静态变量存储在java中的哪里?

c++ - 将 OpenCV 构建为静态库会导致数以千计的 undefined reference

java - Spring 启动MVC : URL not published but shown in the boot logs

java - 使用quickSort时出现stackoverflowerror,我可以增加堆栈和堆吗?

java - Java 客户端<-->服务器套接字的问题

c++ - 为什么这不是正确的生产者消费者模型,以及在我使用 STL 队列时导致错误的原因是什么?

c++ - 将值设置为 static const unsigned int