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

Multithread programming and incrementing a static variable

我已经阅读了几乎所有与我的问题相关的帖子,但无法解决我的问题。此代码是 Big Java - Cay Horstmann 的早期对象中的一个问题。该问题询问有关使用多线程编程计算多个文件的字数并存储组合字数,这是我的问题。

为了获得组合计数器,我使用了一个 static 变量,该变量在线程中每次迭代计算单词时递增。我还使用 ReentrantLock() 使递增一次仅可用于一个线程。 一切正常,除了递增。似乎有时静态变量不会增加。我测试了 lock()unlock() 的数量 每个线程都符合我的预期结果,但是 static 变量无法正常工作。

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

我的task class:

 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)
         {}
     }
 }

这是我的 client class:

    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 class 中的一个实例变量。因此,class 的每个实例都有自己的私有锁,并且它们彼此不同步。最简单的更改是将锁设为静态,就像它保护的变量一样。

您的每个 Runnable 都有自己的锁定对象。为了使您的策略生效,它们都需要共享 一个 锁。

例如,

    // ...
    static Lock ccLock = new ReentrantLock();

    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));
        // ...
    }