【问题标题】:multiple tasks with executor framework带有执行器框架的多个任务
【发布时间】: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


    【解决方案1】:

    你很亲密:

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

    或者:

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

    每个任务都可以像往常一样相互同步,就像您自己在原始线程中运行任务一样。

    请注意ExecutorService 需要Callable 接口而不是Runnable 接口。

    【讨论】:

    • @Travis,invokeAll方法只接收Callable类型的参数,我猜上面的代码会抛出编译错误。
    • @sabarinathanu 不错。我现在已经更正了。
    【解决方案2】:

    我不知道你的锻炼意图。在您的同步版本中。你什么都不同步。两个线程依次访问 TestNotes.txt,因为一次只能打开一个文件进行写入。这是您的意图吗?

    【讨论】:

    • 我的用例是两个线程想要在单个文本文件上写入不同的文本。因此,需要使用执行器框架。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-22
    • 2013-02-13
    • 2017-02-28
    • 1970-01-01
    • 2020-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多