我也是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);
}
}
}
1条答案
按热度按时间w6lpcovy1#
你实际上不需要实现
Runnable
,你只需要确保在你的类上定义一个方法,该方法匹配public void run()
的签名,并为你的任务传递lambda或方法引用。例如,这是可行的:
提交上述任务的呼叫示例:
显然,如果您有
MyClass implements Runnable
和run()方法,只需用途: