运行Thread
完成后,我几乎不需要执行任何操作。因此thread.join()
,我在想要稍后执行的连接线之前使用了关键字。
当我使用join()
关键字运行程序时,“我的应用程序”界面会卡住,直到线程执行完成。我该如何克服这个问题呢?
实际上,我的程序正在执行的操作是,一旦按下按钮,它将执行方法调用,Pass_data_from_java_to_report();
并且在其运行时,Stage
将显示一个单独的视图或出现,以通知用户该程序仍在工作。一旦上述方法完成执行等待,Stage
将通过调用关闭stage.close()
。这些操作工作正常,但使用join关键字冻结。
这是我的第一种方法。
if(event.getSource() == btnAdd){
Stage stage = Waiting(); // Returns Waiting Message
Task <Void> task = new Task<Void>() {
@Override
protected Void call() throws Exception {
Pass_data_from_java_to_report(); // My Method
return null;
}
};
// Displaying Waiting Message
task.setOnRunning(eve -> {
stage.show();
});
// Closing Waiting Message
task.setOnSucceeded(e -> {
stage.close();
});
// Thread for executing task
Thread t1 = new Thread(() -> {
task.run();
});
t1.start();
t1.join(); // if i remove this buddy, there is no freezing
// below from here i want to execute upon thread completion
System.out.println("Finish ");
}
第二种方法
if(event.getSource() == btnAdd){
Stage stage = Waiting();
Thread t1 = new Thread(() -> {
Platform.runLater(() -> {
stage.show();
});
});
Thread t2 = new Thread(() -> {
Pass_data_from_java_to_report(); // My Method
Platform.runLater(() -> {
// Closing the Stage running on another thread upon Above Method Completion
stage.close();
});
});
t1.start();
t2.start();
t1.join(); // These are the Problems
t2.join(); // this one too
System.out.println("Finish ");
}
这是方法
public void Pass_query_to_report(){
try {
// Since method is not time consuming,
// i added 3 sec sleep before the Execution
Thread.sleep(3000);
/*
Some cord
*/
} catch (Exception e) {
e.printStackTrace();
}
}
(注意-我也尝试使用CountDownLatch
但没有运气)
Thread.join()
阻塞当前线程,直到指定线程完成。由于您是在负责渲染UI和处理用户事件的FX Application Thread上调用它的,因此它将阻止该线程,从而使UI无响应。
只需将任务完成后需要执行的代码移到onSucceeded
处理程序即可:
if(event.getSource() == btnAdd){
Stage stage = Waiting(); // Returns Waiting Message
Task <Void> task = new Task<Void>() {
@Override
protected Void call() throws Exception {
Pass_data_from_java_to_report(); // My Method
return null;
}
};
// Displaying Waiting Message
task.setOnRunning(eve -> {
stage.show();
});
// Closing Waiting Message
task.setOnSucceeded(e -> {
stage.close();
// below from here i want to execute upon thread completion
System.out.println("Finish ");
});
// Thread for executing task
Thread t1 = new Thread(task);
t1.start();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句