【问题标题】:Method cannot get updated value from a varible方法无法从变量中获取更新值
【发布时间】:2017-10-17 08:11:02
【问题描述】:

我正在尝试分别计算三个文本文件中的单词数。三个类在多线程中运行。在每个线程中,计数单词的总和将传递给类计数器,并在所有线程完成后更新以将所有计数加到计数器。

我遇到了两个问题,“totalWordCount”可以由类设置器更新。但它不能由同一类的吸气剂得到。另一个问题是我无法检查 Readfiles 线程是否活着。

我在网上搜索过很多次都不能解决,欢迎大家提出意见,非常感谢!

NumberWords 类: 公共课 NumberWords { 私有 int 活动线程; 私人 int 总字数; 私有字符串 getThreadName;

 public NumberWords(int activeThread) {
  this.activeThread = activeThread;
 }

 public synchronized void incTotalWordCount(int n) {
  totalWordCount += n;
  System.out.println("The total word count is " + totalWordCount);
 }

 public synchronized void printCount() {
  System.out.println("The total word count(print count) is " + totalWordCount);
 }

 public synchronized void decActiveThread() {
  getThreadName = Thread.currentThread().getName();
  System.out.println(getThreadName);

  if (Thread.getAllStackTraces().keySet().size() != 0) {
   // Get number of active threads
   activeThread = Thread.getAllStackTraces().keySet().size();

   activeThread--;
   if (activeThread == 0) {
    System.out.println("The total number of word in the three files is " + totalWordCount);
    System.out.println("The active threads is/are " + activeThread);
   }
  }
 }
}

读取文件并统计字数:

    import java.io.FileReader;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;

public class ReadFile1 extends Thread implements Runnable {
 private NumberWords nw;
 public ReadFile1(NumberWords nw) {
  this.nw = nw;
 }

 //set file path
 String path1 = System.getProperty("user.dir") + File.separator + "text1.txt";
 BufferedReader br1 = null;

 public void run() {
  try {
   br1 = new BufferedReader(new FileReader(path1));

   String contentLine = br1.readLine();

   while (contentLine != null) {

    // Count number of words
    String[] parts = contentLine.split(" ");
    int count = 0;
    for (int i = 0; i < parts.length; i++) {
     count++;
    }
    // Check number of words counted.
    System.out.println("The number of words in file(text1.txt) is " + count);

    //Pass words count to sum
    nw.incTotalWordCount(count);
    contentLine = br1.readLine();
   }
  } catch (IOException ioe) {
   ioe.printStackTrace();
  } finally {
   try {
    if (br1 != null) {
     br1.close();
    }
   } catch (IOException ioe) {
    System.out.println("Error in closing the BufferedReader");
   }
  }
 }
}

主类:

public class TestReadFile {
public static void main(String args[]){

NumberWords nw = new NumberWords(args.length);

Thread rf1 = new Thread(new ReadFile1(nw));   
Thread rf2 = new Thread(new ReadFile2(nw));
Thread rf3 = new Thread(new ReadFile3(nw));

    rf1.start();
    rf2.start();
    rf3.start();

    //Get total word cont
    nw.decActiveThread();

  }
}

【问题讨论】:

  • 这些类的格式不是很好。 IDE 可以处理这个问题。不幸的是,它们也不编译。此外,还缺少两个类:ReadFile2ReadFile3。我还不清楚你在问什么。
  • 感谢回复,ReadFile2 & 3 与 ReadFile1 唯一的不同就是读取不同的文本文件,除了这一点都是相同的代码。

标签: java multithreading methods


【解决方案1】:

这个怎么样:

    public class NumberWords {
    private int totalWordCount;
    private int activeThreads;


    public synchronized void incTotalWordCount(int n) {
        totalWordCount += n;
        activeThreads--;
        System.out.println("The total word count is " + totalWordCount);
    }

    public synchronized void printCount() {
        System.out.println("The total word count(print count) is " + totalWordCount);
    }

    public int getActiveThreads() {
        return activeThreads;
    }

    public void setActiveThreads(int activeThreads) {
        this.activeThreads = activeThreads;
    }
}

读取文件:

import java.io.BufferedReader;
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Path;

    public class ReadFile implements Runnable {
        private NumberWords nw;
        private Path filePath;

        public ReadFile(NumberWords nw, Path filePath) {
            this.nw = nw;
            this.filePath = filePath;
        }

        BufferedReader br1 = null;

        public void run() {
            try {
                int count = 0;
                for (String line : Files.readAllLines(filePath)) {
                    String[] parts = line.split(" ");
                    for (String w : parts) {
                        count++;
                    }
                }
                nw.incTotalWordCount(count);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

主要:

import java.io.File;
import java.nio.file.Paths;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
    public static void main(String args[]) throws InterruptedException {

        NumberWords nw = new NumberWords();

        ExecutorService execSvc = Executors.newCachedThreadPool();

        new Thread(new ReadFile(nw, Paths.get(System.getProperty("user.dir") + File.separator + "text1.txt"))).start();
        new Thread(new ReadFile(nw, Paths.get(System.getProperty("user.dir") + File.separator + "text2.txt"))).start();
        new Thread(new ReadFile(nw, Paths.get(System.getProperty("user.dir") + File.separator + "text3.txt"))).start();
        nw.setActiveThreads(3);
        while (nw.getActiveThreads() > 0) {
            Thread.sleep(100);
            System.out.println("Waiting for Tasks to complete!");
        }
        nw.printCount();

    }
}

【讨论】:

  • 嗨,Ben,它工作得很好,非常感谢。也感谢您将 Executor 介绍给活动线程,我会研究它。另一方面,您介意解释一下为什么我无法在原始代码中获得 totalWordCount 吗?对不起,我不明白,再次感谢。
  • 嘿@faifai,你是什么意思?你的意思是你的代码打印出来:字数是:(行中的字)?您应该在 while 循环之外声明 int count 并在 while 循环之后移动 incTotalWordCount。
  • 嗨,本,请注意并立即理解!感谢您的大力帮助!辉
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-16
  • 1970-01-01
  • 2020-07-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多