マルチスレッドを学習するために、Executor Frameworkを使用して2つの異なるタスクを実行するための実装プログラムを作成しました。以前は、同期メソッドを使用してこの要件を満たしていましたが、誤った結果が出ました。次に、Executor Frameworkを使用する方がスレッド管理の方が優れていることを知りました。 Progam以下エグゼキュータフレームワークを使用した複数のタスク
方法
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();
}
}
を同期使用してここでの問題は、私は2つのタスクを実行するExecutorのためのコードを記述するのか分からないです。私は、すなわち
つのタスクを実行するためのExecutorService es = Executors.newFixedThreadPool(5);
public void doStuff() {
es.submit(new MyRunnable());
}
をExecutorServiceのでコードを実装していた最後に、誰かがExecutorのフレームワークを持つ2つの異なるタスクを実装するために私を提案することができますか?
PS:私は運動のあなたの意図を知らない、問題文の
トラヴィス、ありがとうございました。 – Ankit