【发布时间】:2017-01-04 10:20:22
【问题描述】:
我正在编写一个程序来实现使用 Executor Framework 运行两个不同的任务,作为学习多线程的一部分。早些时候,我使用同步方法来满足这个要求,但它给出了错误的结果。然后,我了解到使用 Executor Framework 是更好的线程管理方法。
下面的程序使用同步方法
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();
}
}
这里的问题是我不知道为执行两个任务的 Executor 编写代码。我已经用 ExecutorService 实现了代码来运行单个任务,即
ExecutorService es = Executors.newFixedThreadPool(5);
public void doStuff() {
es.submit(new MyRunnable());
}
最后,有人可以建议我使用 Executor Framework 实现两个不同的任务吗?
PS:如果对理解问题陈述有任何困惑,请告诉我
【问题讨论】:
标签: java multithreading executorservice