2012-01-20 5 views
0

스레드를 통해 두 파일을 동시에 읽는 작업 예제를 제공 할 수 있습니까? 한 번에 읽을 수있는 가장 좋은 방법은 무엇입니까?두 파일을 동시에 Java에서 읽을 수 없습니다.

public static void main(String args[]) { 

     new Runnable(new File("D:/test1.log"),"thread1"); 
     new Runnable(new File("D:/test2.log"),"thread2"); 
    } 

    private static class Runnable implements Runnable { 
     private File logFilePath; 
     Thread runner; 
     // you should inject the file path of the log file to watch 
     public Runnable(File logFilePath,String threadName) { 
      this.logFilePath = logFilePath; 
      runner = new Thread(this, threadName); 
      runner.start(); 
     } 
       _____READ LOGIC HERE____ 

} logs.I 어떤 가깝거나 플러시 사용하고 있지 않다 생성

프로그램.

public final class Slf4jSample { 
    static Logger logger = LoggerFactory.getLogger(Slf4jSample.class); 
    static int i=0; 

    public static void main(final String[] args) { 

      int delay = 0; // delay for 5 sec. 


      int period = 10000; // repeat every sec. 
      Timer timer = new Timer(); 

      timer.scheduleAtFixedRate(new TimerTask() { 
        public void run() { 
         // Task here ... 
         logger.error("error"+i); 
         logger.warn("warn"+i); 
         logger.debug("debug"+i); 
          try{int i=0/0; 
          }catch(Exception e){ 
           logger.error("Ecxeption"+i, e); 
          } 

        i++; 




        } 
       }, delay, period); 
     } 
    } 

답변

3

나는 당신의 목표는 간단한 설명에서 무엇인지 확실히 모르겠지만, 난 그냥, 하나의 하드 디스크에서 병렬 파일을 읽는 것은 일반적으로 좋은 생각이 아니다 있음을 경고하려는 기계 디스크 때문에 머리는 다음 읽기 위치를 찾아야하므로 여러 스레드로 읽기 때문에 속도가 빨라지는 대신 속도가 느려지거나 느려지 게됩니다.

파일의 일부를 읽고 paralle로 처리하려는 경우 여러 소비자 (파일을 처리하기 위해) 한 명의 생산자 (파일을 순차적으로 읽음)를 살펴 보는 것이 좋습니다.

편집 : 여러 독자를 사용하여 주장하는 경우, 당신은 아마 다음과 같은 코드를 변경해야합니다

public static void main(String args[]) { 

    new Thread(new ThreadTask(new File("D:/test1.log")),"thread1").start(); 
    new Thread(new ThreadTask(new File("D:/test2.log")),"thread2").start(); 
} 

private static class ThreadTask implements Runnable { 
    private File logFilePath;   

    // you should inject the file path of the log file to watch 
    public ThreadTask(File logFilePath) { 
     this.logFilePath = logFilePath; 
    } 

    public void run() { 
     // read file 
    } 
} 
+0

하지만이 파일은 계속해서 바뀌고 있습니다. 매번 업데이트 된 데이터를 가져와야합니다. – Rookie

+0

@raghav, Ok, 프로그램을 작동시키는 방법을 편집했습니다. – Tudor

+0

나는 이것을 시도하고있다. .. 당신은 – Rookie

3

당신은 Thread t = new Thread(new Runnable(.....)) 같은 스레드 객체를 생성하고 스레드의 생성자에서 실행 가능한 개체를 전달할 수 있습니다. 그런 다음 스레드 객체에서 start 메소드를 호출하면 별도의 스레드가 시작되고 Runnable의 run 메소드가 호출됩니다.

Runnable의 생성자 안에 새로운 스레드를 생성하면 안됩니다.

+0

이 방법으로도 작동하지 않습니다. – Rookie

관련 문제