在我的JavaFx应用程序中,我面临一个问题。
序言:我不想只针对我的应用程序,而是希望被概括,这样像我这样的人就会对类似的情况有一个想法。
后台:使用fxml文件和多线程概念实现Javafx应用程序。
汇总:我尝试了一个应用程序,它基本上使用多线程来完成一些任务,一旦多线程完成,它就会依次转移到另一个任务。在进行多线程时,主GUI会冻结。
我做了什么,
//This is Main class
Parent Root -> defined on top
public Parent createContent(){
try{
root = FXMLLoader.load(getClass().getResource("Layout.fxml"));
}catch { .....}
}
public void start(){
stage.setScene(new Scene(createContent()));
Task<Void> task = new Task<Void>() {
@Override
public Void call() throws Exception {
Thread.sleep(1000);
return null ;
}
};
task.setOnSucceeded(event->{
stage.show();
});
new Thread(task).run();
}
public static void main(String[] args) {
launch(args);
}
// This is inside the controller on button click event
@FXML
private void start(ActionEvent event) { <---- This one is button click event
Thread t1 = new Thread(new Mul());
t1.start();
Thread t2 = new Thread (new Mul());
t2.start();
}
// Finally
public class Mul implements Runnable {
public void type() {
for (int a = 0; a < 200000; a++) {
System.out.println( Thread.currentThread().getName()+ " says " + a);
}
}
@Override
public void run() {
type();
}
}
现在,这是结果。如果我只是从控制器启动线程,那么当线程在后台运行时,我的主应用程序不会冻结。但是,由于应用程序按顺序运行,也就是说,只有当线程完成其工作时,下一步才能工作。
我可以使用t1.join()和t2.join(),但是这样做会冻结我的主应用程序(这里的主应用程序是主GUI),在线程完成之前我不能继续使用它。
什么是最优的解决方案,这样我就可以在不阻塞主应用程序或的情况下使用多线程,在这里做错了什么?(info,我是通过跟踪Stack overflow和google的不同建议得出这个解决方案的)
发布于 2015-06-26 12:10:20
为什么不做呢
Task<Void> task = new Task<Void>() {
@Override
public Void call() {
Mul m1 = new Mul();
m1.run();
Mul m2 = new Mul();
m2.run();
return null ;
}
};
new Thread(task).start();
如果您真的想“链接”不同的任务,请从另一个的onSucceeded
处理程序中调用其中一个:
Task<Void> task1 = new Task<Void>() {
@Override
public Void call() {
new Mul().run();
return null ;
}
};
Task <Void> task2 = new Task<Void>() {
@Override
public Void call() {
new Mul().run();
return null ;
}
};
task1.setOnSucceeded(e -> new Thread(task2).start());
new Thread(task1).start();
显然,如果您将Mul
作为一个Task
子类而不是一个Runnable
,并且最好使用带有守护进程线程等的Executor
,那么这是比较干净的,但是这应该给您提供了一个想法。
https://stackoverflow.com/questions/31068839
复制相似问题