从threadExecutor返回值

时间:2012-03-12 21:16:28

标签: java multithreading executor

如何在固定的threadExecutor中访问getOptimizedMol()方法?我需要在每个优化器线程结束时获得返回分子?

import chemaxon.marvin.calculations.ConformerPlugin;
import chemaxon.marvin.plugin.PluginException;
import chemaxon.struc.Molecule;

public class Optimizer3D implements Runnable {


    private Molecule mol3D;
    private Molecule mol2D;

    Optimizer3D(Molecule mol2D_)
    {
       this.mol2D = mol2D_; 
    }

    @Override
    public void run() {
        mol3D = chemAxonOptimizer();
    }

    private Molecule chemAxonOptimizer()
    {
        //optimize molecule code not shown
        return molecule;

    }


    public Molecule getOptimizedMol()
    {
        return mol3D;
    }
}

3 个答案:

答案 0 :(得分:1)

一种简单的技术是将某种JobListener添加到runnable中:

public class Optimizer3D implements Runnable {

    public static interface JobListener {
         public void onJobFinished(Optimizer3D job);
    }

    private Molecule mol3D;
    private Molecule mol2D;
    private JobListener jobListener;
    Optimizer3D(Molecule mol2D_, JobListener listener)
    {
       this.mol2D = mol2D_; 
       this.jobListener = listener;
    }

    @Override
    public void run() {
        mol3D = chemAxonOptimizer();
        if (jobListener!=null) {
            jobListener.onJobFinished(this);
        }
    }

    private Molecule chemAxonOptimizer()
    {
        //optimize molecule code not shown
        return molecule;

    }


    public Molecule getOptimizedMol()
    {
        return mol3D;
    }
}

答案 1 :(得分:1)

您需要Callable而不是RunnableCallable会返回您的结果。

您可以按照以下方式获取:

Future<YourExpectedResult> future = executor.submit(new YourCallable());
YourExpectedResult result = future.get();

答案 2 :(得分:0)

使用Callable:

public class Optimizer3D implements Callable<Molecule>{
    private Molecule mol3D;
    private Molecule mol2D;

    Optimizer3D(Molecule mol2D_)
    {
       this.mol2D = mol2D_; 
    }

    @Override
    public Molecule call() {
        mol3D = chemAxonOptimizer();
        return getOptimizedMol();
    }

    private Molecule chemAxonOptimizer()
    {
        //optimize molecule code not shown
        return molecule;

    }


    private Molecule getOptimizedMol()
    {
        return mol3D;
    }
}

然后从你的执行官那里:

Future<Molecule > future = executor.submit(yourTask);
Molecule  yourValue = future.get();