Java:Threadpoolexecutor-使用作业列表提交作业?

时间:2018-10-27 09:57:36

标签: java executorservice threadpoolexecutor

以下代码是CustomerjobManager。客户有一个姓名,一个地址和一个帐户余额。工作是从一个客户到另一个客户的资金转移。这是一个Threadpoolexecutor培训计划。以下版本有效,我一个接一个地提交作业。

customer.java

public class customer {

    private String name;
    private String adress;
    private Double accountBalance;

    public customer(String name, String adress, Double accountBalance)
    {
        this.name = name;
        this.adress = adress;
        this.accountBalance = accountBalance;
    }

    public String getName() { return name; }

    public String getAdress()
    {
        return adress;
    }

    public Double getAccountBalance(){return accountBalance;}

    public void setAccountBalance(double accountBalance){this.accountBalance=accountBalance;}

    @Override
    public String toString(){

        return "[" + name+"; " +adress+"; "+accountBalance+"]";
    }
}

customerOrganizer.java

import java.util.ArrayList;
import java.util.List;

public class customerOrganizer {

    private static final customerOrganizer myJobOrganizer = new customerOrganizer();

    public static customerOrganizer getJobOrganizer(){
        return myJobOrganizer;
    }

    private List<customer> customerList = new ArrayList<customer>();

    public void add_customer(customer kunde)
    {
        this.customerList.add(kunde);
    }

    public Iterable<customer> all_customers()
    {
        return this.customerList;
    }

    public static customerOrganizer getInstance()
    {
        return myJobOrganizer;
    }

}

job.java

public class job implements Runnable {
    private customer kunde1;
    private customer kunde2;
    private Double transfer;

    public job(customer kunde1, customer kunde2, Double transfer) {
        this.kunde1 = kunde1;
        this.kunde2 = kunde2;
        this.transfer = transfer;
    }

    @Override
    public String toString(){

        return "[" + kunde1+"; " +kunde2+"; "+transfer+"]";
    }

    public void run() {

        System.out.println("Starting transfer");

        Double geber = this.kunde1.getAccountBalance();
        Double nehmer = this.kunde2.getAccountBalance();

        Double geberNeu = geber - this.transfer;
        this.kunde1.setAccountBalance(geberNeu);

        Double nehmerNeu = nehmer + this.transfer;
        this.kunde2.setAccountBalance(nehmerNeu);
        System.out.println("Transfer done");
    }
}

jobOrganizer.java

public class jobOrganizer {

    private static final jobOrganizer myJobOrganizer = new jobOrganizer();

    public static jobOrganizer getMyJobOrganizer() {
        return myJobOrganizer;
    }

    private List<job> jobList = new ArrayList<job>();

    public int getAmount(){ return jobList.size();}

    public void add_job(job newJob) {
        this.jobList.add(newJob);
    }

    public Iterable<job> all_jobs() {
        return this.jobList;
    }

    public static jobOrganizer getInstance() {
        return myJobOrganizer;
    }

}

Main.java

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {

    public static void main(String[] args) {
        customerOrganizer myCustomerOrganizer = new customerOrganizer();
        jobOrganizer myJobOrganizer= new jobOrganizer();

        customer mueller = new customer("Tim Mueller", "Strasse 1", 1077.00);
        customer john = new customer("John Doe", "Strasse 2",503.00);
        customer meier = new customer("John Meier", "Strasse 3", 8500.50);
        customer wurst = new customer("Hans Wurst", "Strasse 4", 1000.00);

        myCustomerOrganizer.add_customer(mueller);
        myCustomerOrganizer.add_customer(john);
        myCustomerOrganizer.add_customer(meier);
        myCustomerOrganizer.add_customer(wurst);

        job transfer1= new job(meier,wurst,500.50);
        job transfer2= new job(mueller,john,77.00);

        myJobOrganizer.add_job(transfer1);
        myJobOrganizer.add_job(transfer2);

        // this works:
        ExecutorService executor = Executors.newFixedThreadPool(2);
        executor.submit(transfer1);
        executor.submit(transfer2);
        executor.shutdown();


    }}

所以,我确实有一个jobList,我有一个应该使用它的想法。我不想一一递交工作,而是根据工作清单提交工作。一开始我想到的是这样的东西:

 int threads = myJobOrganizer.getAmount();
        ExecutorService executor = Executors.newFixedThreadPool(threads);
        for (int i = 0; i <threads+1; i++){
            //submit jobs? execute?
        }

此外,myJobOrganizer是否需要实现Runnable?我还看到解决方案是这样的:

for(condition){

        executor.execute(new Runnable() {

            @Override
            public void run() {
              submit the jobs?
                }
            }}

但是我真的不知道该怎么做。基本上,我不知道如何以正确的方式从我的jobList中提取作业,以便我可以将其提交给执行者服务>。<< / p>

有关线程安全性的更新

因此,我按了Rab提供的链接,我使用了CompletionService。现在Main.java的最后一部分看起来像这样:

int threads = myJobOrganizer.getAmount();

System.out.println(myCustomerOrganizer.all_customers().toString());
// executor service   
ExecutorService executor = Executors.newFixedThreadPool(threads);
// completion service is applied on executor
CompletionService service = new ExecutorCompletionService(executor);

for(Callable<Job> myJob : myJobOrganizer.all_jobs()){
    service.submit(myJob);
}
executor.shutdown();
// pause the main for control printout -> not nice yet, I am working on 
// joining threads
try {
    Thread.sleep(1000);
} catch (InterruptedException e) {
    e.printStackTrace();
}
// control print
System.out.println(myCustomerOrganizer.all_customers().toString());

请注意,此编辑是为了完成输入,但仍然是错误的(可悲的)。提供的答案与原始问题相关,与线程安全性无关

感谢您的时间和精力!

2 个答案:

答案 0 :(得分:3)

ExecutorService处理如何在工作人员之间分配任务。您所需要做的就是一步一步地传递工作。

for (job jobObj : myJobOrganizer.all_jobs()) 
    executor.submit(jobObj);

请注意,sumbit返回一个Future<?>,该信息用于跟踪您的任务是否完成或是否出错(以及任务结果,但可运行但没有结果)。如果您关心这些事情,则可能希望将它们收集在某种容器中,例如List


如果将job更改为Callable<Void>,则提交将更加容易。 Callable是Runnable的某种扩展,它允许任务在完成时产生结果。由于您的传输没有结果,因此可以使用java.lang.Void作为通用参数的填充类型。

现在,只需executor.invokeAll(myJobOrganizer.all_jobs())就足够了。这样可以节省一些上下文切换,从而加快了速度。 (实际上非​​常重要,因为您的任务非常小)


顺便说一句,您应该意识到并发访问需要适当的同步,而您没有同步。如果不同的工作涉及一个相同的帐户,则您的帐户可能会处于错误的状态。我们也通常在LargeCamelCase中命名类,在smallCamelCase中命名方法。

答案 1 :(得分:0)

如果您不想使用循环,则可以使用Stream进行。如果您使用的Java版本大于或等于8,请参见

    myJobList
            .stream()
            .forEach(e -> executor.execute(() -> {
        //submit the jobs
    }));

    myJobOrganizer.all_jobs()
            .stream()
            .forEach(e -> executor.submit(e));

如果您确实不想循环,则可以使用executor.invokeAll(myJobList)提交列表。

我怎么发现这个答案很有趣,您应该完全研究它https://stackoverflow.com/a/34798567/6895166