带executor框架的多任务

tmb3ates  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(319)

我正在编写一个程序来实现运行两个不同的任务,其中executor框架是学习多线程的一部分。早些时候,我使用synchronized方法来满足这个需求,但是它给出了错误的结果。然后,我了解到使用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();

        }
    }

这里的问题是我不知道如何为执行两个任务的执行器编写代码。我已经用executorservice实现了运行单个任务的代码。

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

        es.submit(new MyRunnable());

    }

最后,有人能建议我用executor框架实现两个不同的任务吗?
ps:如果对问题陈述的理解有任何混乱,请告诉我

vfwfrxfs

vfwfrxfs1#

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

kjthegm6

kjthegm62#

你很接近:

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 接口。

相关问题