멀티 스레딩을 배우기 위해 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 : 제가 운동의 의도를 모르는 이해 문제 설명
감사합니다 트래비스, 이제 제대로 작동합니다. – Ankit