2017-01-04 1 views
0

멀티 스레딩을 배우기 위해 Executor Framework로 두 가지 다른 작업을 실행하기 위해 구현할 프로그램을 작성했습니다. 이전에는이 ​​요구 사항을 채우기 위해 동기화 된 메서드를 사용했지만 잘못된 결과가 나타났습니다. 그런 다음 Executor Framework를 사용하면 스레드 관리에 더 나은 방법이라는 것을 알게되었습니다. 방법Executor 프레임 워크를 사용한 여러 작업

import java.io.*; 
import java.util.Scanner; 
import java.nio.*; 
class FileWriteThreadExample implements Runnable{ 
    /*This class needs to write some content into text file*/ 

    public synchronized void run() { 
      StringBuilder thisProgamMessage = new StringBuilder(); 

      try(FileWriter fw = new FileWriter("C:\\TestNotes.txt", true); 
       BufferedWriter bw = new BufferedWriter(fw); 
       PrintWriter out = new PrintWriter(bw)) 
      { 
       for(int i=1; i<=50;i++){ 
        //Thread.sleep(500); 
        //System.out.println(i); 

        thisProgamMessage.append(i+":"+Math.random()+"\n"); 

       } 
       out.println(thisProgamMessage.toString()); 
      } catch (IOException e) { 
       //exception handling left as an exercise for the reader 
      } 

    } 
} 

class FileWriteThreadExample2 implements Runnable{ 
    /*This class needs to write some content into text file*/ 

    public synchronized void run() { 
      StringBuilder thisProgamMessage = new StringBuilder(); 
      try(FileWriter fw = new FileWriter("C:\\TestNotes.txt", true); 
       BufferedWriter bw = new BufferedWriter(fw); 
       PrintWriter out = new PrintWriter(bw)) 
      { 


       System.out.println("Starting Second Write Thread Task"); 
       for(int i=50; i>=1;i--){ 
        //Thread.sleep(500); 
        //System.out.println(i); 
        thisProgamMessage.append(i+"====>"+Math.random()+"\n"); 
       } 
       out.println(thisProgamMessage.toString()); 
       System.out.println("Completing Second Write Thread Task"); 
      } 
      catch (FileNotFoundException fnfe){ 
       fnfe.printStackTrace(); 
      } 
      catch(IOException ioex) { 
       ioex.printStackTrace(); 
      } 
      /*catch(InterruptedException ie){ 
       ie.printStackTrace(); 
      }*/  
    } 
} 
class SynchronizeTest { 
     public static void main (String[] args) { 
      FileWriteThreadExample t1 = new FileWriteThreadExample(); 
      FileWriteThreadExample2 t2 = new FileWriteThreadExample2(); 

      t1.start(); 

      t2.start(); 

     } 
    } 

여기 문제 나는이 작업을 실행 집행자에 대한 코드를 작성 몰라 동기화 사용 Progam 아래

. 나는 하나의 작업 즉

ExecutorService es = Executors.newFixedThreadPool(5); 
    public void doStuff() { 


     es.submit(new MyRunnable()); 


    } 

마지막으로, 누군가가 집행자 프레임 워크와 두 개의 서로 다른 작업을 구현하기 위해 저를 제안 할 수 있습니다를 실행하는 ExecutorService를 사용하여 코드를 구현했다?

PS : 제가 운동의 의도를 모르는 이해 문제 설명

답변

1

당신은 매우 가까운 위치 :

ExecutorService es = Executors.newFixedThreadPool(5); 
public void doStuff() { 
    es.submit(new FirstTask()); // FirstTask implements Runnable 
    es.submit(new SecondTask()); // SecondTask implements Runnable 
} 

또는 대안 : 당신이 원시 스레드에서 자신을 작업을 실행하는 것처럼

ExecutorService es = Executors.newFixedThreadPool(5); 
public void doStuff() { 
    Collection<Runnable> tasks = Arrays.asList(new Runnable[] 
      { new FirstTask(), new SecondTask() }); 
    es.invokeAll(tasks); 
} 

각 작업은 보통 같은 서로 동기화 할 수 있습니다.

+0

감사합니다 트래비스, 이제 제대로 작동합니다. – Ankit

0

에 혼란을 알려주십시오. 귀하의 동기화 버전. 너는 아무것도 동기화하지 않았다. 두 스레드는 TestNotes.txt에 순차적으로 액세스합니다. 단 하나의 파일 만 쓰기 위해 파일을 열 수 있기 때문입니다.이 의도입니까?

+0

내 사용 사례는 두 개의 스레드가 단일 텍스트 파일에 다른 텍스트를 쓰려고합니다. 따라서 Executor 프레임 워크를 사용해야합니다. – Ankit

관련 문제