我想寻求如何设计应用程序的建议。目前,我想将处理大数据的统计应用程序重写为多线程版本。我的主要语言是 C++,很抱歉我的问题有点初学者:-)。
现有应用程序基于以下模型。有一个 MainWindow 类连续显示涉及当前缩放操作(GUI)的先前结果。每个统计计算都基于自己的类,拾取输入数据、执行计算、显示结果及其可视化(基于 swing)。
不幸的是,该库不是以多线程形式编写的。它有一个不良后果:当计算运行时,无法使用 MainWindow(浏览所有结果,直到获得新结果);它被“卡住”了......
昨天,我试图提出一个概念更新:
public class MainWindow extends JFame {
private void fButtonActionPerformed(java.awt.event.ActionEvent e) {
//Get data, single thread
Matrix A = getData(); //Input data (block matrix)
Matrix B; //Output data (block matrix)
//Computation in a separate thread
FunctionMT f = new FunctionMT (A, B);
Thread t = new Thread(f);
t.start(); // Starting the thread
//Display results in a form
results.print(B);
//Update graphic results
scene.update(B);
scene.repaint();
}
示例函数类FunctionMT扩展了Thread库
public class FunctionMT extends Thread{
private final Matrix A;
private Matrix B;
public FunctionMT (final Matrix A_, Matrix B_) {A = A_; B = B_;}
public void run () { spDecomposition();}
public void spDecomposition() {
for (int i = 0; i < A.size; i++)
for (int j = 0; j < A.size; j++)
B(i,j) = f(A(i,));} //Some computationally hard step
}
矩阵A是输入矩阵,B代表输出。计算是在使用 FunctionMT 实例的单个线程中执行的...
当计算在单线程中运行时,可以使用主窗口。不幸的是,在计算停止之前结果被重新绘制。
我尝试添加一个连接方法()
...
Thread t = new Thread(f);
t.start(); // Starting the thread
try{t.join();} //Wait for its end
catch(InterruptedException e) {e.printStackTrace();}
results.print(B);
scene.update(B);
scene.repaint();
...
等待结果被处理。不幸的是,它使主窗口卡住。
如何提出多线程计算以便能够在计算期间与主窗口一起工作以及表单等待计算完成?
是否可以在for循环中添加一些处理系统消息的函数?
for (int i = 0; i < A.size; i++)
for (int j = 0; j < A.size; j++)
processSystemMessages();
B(i,j) = f(A(i,));}
另一个解决方案可能会加入计算算法并将结果显示到同一个线程中,但它看起来很丑:-)并且破坏了设计模式。
非常感谢您的帮助...
最佳答案
试试这个:
更新:松散耦合
public class MainWindow extends JFrame {
private void fButtonActionPerformed(java.awt.event.ActionEvent e) {
// ...
FunctionMT f = new FunctionMT (A, B, new Runnable() {
@Override
public void run() {
results.print(B);
scene.update(B);
scene.repaint();
}
});
Thread t = new Thread(f);
t.start();
// Wait for computation:
// won't do it here.
// results.print(B);
// scene.update(B);
// scene.repaint();
}
}
public class FunctionMT extends Runnable {
// ...
private Runnable callback;
public FunctionMT (final Matrix A_, Matrix B_, Runnable callback) {
// ...
this.callback = callback;
}
private void spDecomposition() {
// Do computation.
SwingUtilities.invokeLater(callback);
}
}
关于Java,多线程应用程序,计算时工作主窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40562392/