gpt4 book ai didi

java - 单独类中的线程如何将数据传递给主类

转载 作者:行者123 更新时间:2023-12-01 11:35:51 24 4
gpt4 key购买 nike

我编写了下面的代码,我的问题是,我想将数据从 FICSR 类传递到主类。我尝试在 FICSR 类的构造函数中声明“在 calcFICS() 方法内部提到”的 ArrayList,但之后我发现我无法在内部使用它们calcFICS() 方法,为什么?以及如何解决。

主类:

    public static void main(String[] args) {
MatFactory matFactory = new MatFactory();
FilePathUtils.addInputPath(path_Obj);
Mat bgrMat = matFactory.newMat(FilePathUtils.getInputFileFullPathList().get(0));

if (bgrMat != null) {
if (!bgrMat.empty()) {
fiCSR = new FICSR(bgrMat, SysConsts.MIN_CS_RADIUS);
} else {
Log.E(TAG, "MainClass", "bgrMat is empty");
}
} else {
Log.E(TAG, "MainClass", "bgrMat is null");
}

FICSR 类别:

    public FICSR(Mat bgrMat, int csRadius) {
// TODO Auto-generated constructor stub
this.bgrMat = bgrMat;
this.csRadius = csRadius;

this.fiCS_R3 = new Thread(new FICS(this.bgrMat, this.csRadius), "FICS_R" + this.csRadius);
fiCS_R3.start();
}

private class FICS implements Runnable {

private Mat bgrMat;
private int csRadius;

public FICS(Mat bgrMat, int csRadius) {
// TODO Auto-generated constructor stub
this.bgrMat = bgrMat;
this.csRadius = csRadius;
}

public void run() {
// TODO Auto-generated method stub
calcFICS(this.bgrMat, this.csRadius);
}

public static void calcFICS(Mat bgrMat, int csRadius) {
// TODO Auto-generated method stub

ArrayList<Mat> onOffCSActRegMatsList = null;
ArrayList<Mat> offOnCSActRegMatsList = null;

ArrayList<Mat> onOffCSFullMatsList = null;
ArrayList<Mat> offOnCSFullMatsList = null;

onOffCSActRegMatsList = new ArrayList<Mat>();
offOnCSActRegMatsList = new ArrayList<Mat>();

onOffCSFullMatsList = new ArrayList<Mat>();
offOnCSFullMatsList = new ArrayList<Mat>();

//here I want to add values to the ArrayLists defined above and return them to the main class. how can I do that?

.........

最佳答案

您无法访问它,因为 calcFICS 是静态的,并且您无法从静态方法访问非静态字段。但如果你想在工作线程中进行计算以利用所有 CPU 核心,更好的解决方案是使用 ExecutorService,例如一个 ForkJoinPool。

FICS 类:

class FICS {
static class Result {
ArrayList<Mat> onOffCSActRegMatsList;
ArrayList<Mat> offOnCSActRegMatsList;
ArrayList<Mat> onOffCSFullMatsList;
ArrayList<Mat> offOnCSFullMatsList;
}

public static Result calcFICS(Mat bgrMat, int csRadius) {
Result result = new Result();
result.onOffCSActRegMatsList = new ArrayList<Mat>();
result.offOnCSActRegMatsList = new ArrayList<Mat>();

result.onOffCSFullMatsList = new ArrayList<Mat>();
result.offOnCSFullMatsList = new ArrayList<Mat>();
//add values to the ArrayLists
return result;
}
}

主类:

...
ForkJoinPool pool = new ForkJoinPool();
Future<FICS.Result> fut = pool.submit(() -> FICS.calcFICS(bgrMat, SysConsts.MIN_CS_RADIUS));
FICS.Result result = fut.get();
...

fut.get() 会阻塞主线程,直到计算完成。但是您可以在调用任何 get 方法之前向池中提交多个计算。

关于java - 单独类中的线程如何将数据传递给主类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30002506/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com