java - 具有执行器框架的多个任务

标签 java multithreading executorservice

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

        }
    }

这里的问题是我不知道为执行两个任务的执行器编写代码。我已经使用 ExecutorService 实现了用于运行单个任务的代码,即

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


        es.submit(new MyRunnable());


    }

最后,有人可以建议我使用 Executor Framework 实现两个不同的任务吗?

PS:如果在理解问题陈述时有任何困惑,请告诉我

最佳答案

你已经很接近了:

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 接口(interface),而不是 Runnable 接口(interface)。

关于java - 具有执行器框架的多个任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41461410/

相关文章:

java - 大量静态存储的值是否会产生缩放问题

c++ - 同时运行不同的线程,无需等待其他线程完成

java - 同步多线程服务器

ios - NSFetchRequest 返回旧数据,即使数据库已更新

Java ExecutorService堆空间问题

java - ThreadPoolExecutor 在队列满时阻塞?

java - ExecutorService 变慢,使我的电脑陷入困境

Java null 取消引用 - 微焦点安全漏洞

java - 如何从两个 n 位二进制数创建一个 2n 二进制数?

java - 正则表达式查找方法