在Java中将类方法放入ThreadPoolExecutor

hfyxw5xn  于 2023-01-04  发布在  Java
关注(0)|答案(1)|浏览(104)

我也是Java和多线程的新手。我读过关于ThreadPool的文章,看到我可以提交/执行lambda函数到ThreadPoolExecutor中。但是我如何在Java中为类方法做这件事呢?

public class ParallelPointSystem{
    private ArrayList<Cluster> clusters;
    private ArrayList<Point> points;
    private int dimension;
    private int clusters_amount;
    private int iterations;

    private void attach_point(int i) throws Exception {
        double distance = Point.get_distance(this.points.get(i), this.clusters.get(0).get_current_center());
        int ind = 0;
        for(int j = 1; j < clusters_amount; j++){
            double dst = Point.get_distance(this.points.get(i), this.clusters.get(j).get_current_center());
            if(distance > dst){
                distance = dst;
                ind = j;
            }
        }
        this.clusters.get(ind).attach(this.points.get(i));
    }
}

我试图将一个方法 Package 在一个实现Runnable接口的类中,但这是唯一的方法吗?我做得对吗?

class Attach_Point implements Runnable{

    private int i;
    private ArrayList<Cluster> clusters;
    private ArrayList<Point> points;
    private int clusters_amount;
    public Attach_Point(int i, ArrayList<Cluster> clusters, ArrayList<Point> points, int cluster_amount){
        this.i = i;
        this.clusters = clusters;
        this.points = points;
        this.clusters_amount = cluster_amount;
    }

    @Override
     public void run(){
        double distance = Point.get_distance(this.points.get(i), this.clusters.get(0).get_current_center());
        int ind = 0;
        for(int j = 1; j < clusters_amount; j++){
            double dst = Point.get_distance(this.points.get(i), this.clusters.get(j).get_current_center());
            if(distance > dst){
                distance = dst;
                ind = j;
            }
        }
        try {
            this.clusters.get(ind).attach(this.points.get(i));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
 }
w6lpcovy

w6lpcovy1#

你实际上不需要实现Runnable,你只需要确保在你的类上定义一个方法,该方法匹配public void run()的签名,并为你的任务传递lambda或方法引用。
例如,这是可行的:

class MyClass {
   public void doIt() {
       System.out.println("Hello "+this+" in "+Thread.currentThread());
   }
}

提交上述任务的呼叫示例:

ExecutorService pool = Executors.newFixedThreadPool(1);

// Submit as method reference:
pool.execute(new MyClass()::doIt);

MyClass obj = new MyClass();

// Submit as Runnable lambda:
pool.execute(() -> obj.doIt());

显然,如果您有MyClass implements Runnable和run()方法,只需用途:

pool.execute(obj);

相关问题