2017-04-02 35 views
-1

我想讀取和打印在csv文件中的行。我需要使用多線程的相同。文件中有10行,如果我提供2個線程(no的線程是依賴於用戶輸入的),它應該讀取所​​有10行,每行應該被任何線程讀取和打印一次。無法讀取在java中使用多線程的行

但我無法成功執行它。如果我提供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..."); 
      } 
     } 

    } 

} 

在此先感謝。

+0

爲什麼?這太瘋狂了。使用單個線程。 – EJP

回答

0

您將需要構建一個線程「鎖定」,以便線程完成後,即使下一個線程就緒,它也可以完成寫入。你可以使用'等待'和'通知'來建立這個。在使用print/println之前插入代碼來檢查線程是否準備就緒,並向所有其他線程發送「等待」信號。這將導致線程不再發生碰撞並保持代碼輸出的清潔。

一個偉大的在線資源,這將有助於學習如何構建到你的代碼,這是位於:https://www.youtube.com/watch?v=fjMTaVykOpc

+0

感謝您的答覆。請您介紹一下上述程序的線程鎖定。 –