无法在java中使用多线程读取行

时间:2017-04-02 05:49:37

标签: java multithreading

我正在尝试读取和打印csv文件中的行。我需要使用多线程。文件中有10行,如果我提供2个线程(没有线程是用户输入依赖的)它应该读取所​​有10行,其中每行应该由任何一个线程读取和打印一次。

但是我无法成功执行它。如果我提供2个线程,它将读取2行(随机行),不读取剩余的并终止程序。 我正在尝试为它编写代码。

主要课程:

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ThreadMain implements Runnable {

    String name;
    static Map<Integer, Boolean> map = new HashMap<Integer, Boolean>();

    public synchronized static Map<Integer, Boolean> getMap() {
        return map;
    }

    public synchronized static void setMap(Map<Integer, Boolean> map) {
        ThreadMain.map = map;
    }

    public ThreadMain(String s) {
        name = s;
    }

    public void run() {
        ThreadReader.Reader(name);
    }

    @SuppressWarnings("rawtypes")
    public static void main(String[] args) {

        Scanner scan = null;
        boolean repeat = false;
        int threads;

        do {
            try {
                scan = new Scanner(System.in);
                System.out.print("Enter no. of threads: ");
                threads = Integer.parseInt(scan.nextLine());

                // Initializing map
                int i;
                for (i = 1; i <= 10; i++) {
                    map.put(i, false);
                }

                ExecutorService executor = Executors.newFixedThreadPool(threads);
                for (i = 1; i <= threads; i++) {
                    executor.execute(new ThreadMain("Thread #" + "is "+i));
                    System.out.println("Started Thread: " + i);
                }

                executor.shutdown();
                while (!executor.isTerminated()) {
                }
                try {
                   executor.awaitTermination(5, TimeUnit.NANOSECONDS);
                } catch (InterruptedException e) {
                    System.out.println("Error in terminating threads...");
                }
                // System.out.println(finished);

                // Printing key-value pairs
                // Set set = map.entrySet();
                Set set = ThreadMain.getMap().entrySet();
                Iterator iterator = set.iterator();
                while (iterator.hasNext()) {
                    Map.Entry mentry = (Map.Entry) iterator.next();
                    System.out.print("Key: " + mentry.getKey()  );
                    System.out.println(" & Value: "+mentry.getValue());
                }
            } catch (NumberFormatException e) {
                repeat = true;
                System.out.println("Invalid number format...");
                System.out.println("");
            } catch (IllegalArgumentException e) {
                repeat = true;
                System.out.println("Invalid input format...");
                System.out.println("");
            } catch (Exception e) {
                System.out.println("Error...");
                // e.printStackTrace();
            }
        } while (repeat);

        scan.close();
    }

}

文件读取(可运行的类):

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Random;

public class ThreadReader {

    public static void Reader(String threadName) {

       // ThreadReaderCheck check = null;
        BufferedReader br = null;
        String line = null;
        Random rand;
        int randomInt;
        boolean generate;
        int i;

        try {
            //check = new ThreadReaderCheck();
            br = new BufferedReader(new FileReader("ThreadCSV.csv"));
                synchronized (br) {
                    // Generating random number
                    generate = false;
                    rand = new Random();

                    do {
                        randomInt = rand.nextInt(11);

                        if (randomInt == 0) {
                            generate = true;
                        } else {
                            System.out.println(threadName + " " + randomInt);
                            if (randomInt > 0 && randomInt < 11) {
                                line = br.readLine();
                                System.out.println(threadName + " " + ThreadMain.map.get(randomInt));
                                if (ThreadMain.map.get(randomInt) == false) {
                                    for (i = 1; i < randomInt; i++) {
                                        line = br.readLine();
                                    }
                                    if (line != null) {
                                        ThreadMain.map.put(randomInt, true);
                                        System.out.println(threadName + " " + line);
                                        Thread.sleep(1000);
                                        br.notifyAll();
                                    }
                                } else {
                                    generate = true;
                                }
                            }
                        }
                    } while (generate);
                }
        } catch (Exception e) {
            System.out.println("Error in reading from file...");
        } finally {
            try {
                br.close();
            } catch (Exception e) {
                System.out.println("Error while closing file...");
            }
        }

    }

}

先谢谢。

1 个答案:

答案 0 :(得分:0)

你需要建立一个线程&#39;锁定&#39;这样一旦一个线程完成,它就可以完成写入,即使下一个线程准备好了。您可以使用等待&#39;并且&#39;通知&#39;建立这个。在使用print / println之前插入代码以检查线程是否准备好并发送所有其他线程“等待”。信号。这将导致线程不再发生冲突并保持代码输出清洁。

可以在以下网址找到一个很棒的在线资源,可以帮助我们了解如何将其构建到您的代码中:https://www.youtube.com/watch?v=fjMTaVykOpc