JavaFX:多次使用线程 [英] JavaFX : Use a Thread more than once
问题描述
我是JavaFX的新手,我对线程有点问题:我可以执行两次而且找不到原因。
I'm new with JavaFX and I've a little problem with a thread: I can execute it twice and I can't find why.
这是我的代码的总和:
Task<Void> task = new Task<Void>() {
@Override public Void call() throws ImageLoadedException, HomographyException, IOException {
try{
System.out.println("GO !");
return null;
}
catch (Exception e){
e.printStackTrace();
}
return null;
}
@Override
protected void succeeded() {
super.succeeded();
System.out.println("SUCCEEDED");
}
};
@FXML protected void launch(ActionEvent event){
new Thread(task).start();
}
当我第一次点击启动我的线程的按钮时,我的任务运行没有任何问题(我的控制台显示GO!和SUCCEEDED)。
When I click a first time the button who start my thread, my task run without any problem (my console display "GO !" and "SUCCEEDED").
但是,如果我再次点击,则没有任何附加信息。难道我做错了什么 ?我们不能多次使用一个线程吗?
But if I click a second time, nothing append. Am I doing something wrong ? Can't we use a thread more than once ?
推荐答案
来自 Thread.start()文档:否
多次启动一个线程永远不合法。特别是,
线程一旦完成执行就不会重新启动。
It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.
来自 JavaFX中的并发教程:
Task类定义了一个无法重用的一次性对象。如果
需要一个可重用的Worker对象,请使用Service类。
The Task class defines a one-time object that cannot be reused. If you need a reusable Worker object, use the Service class.
So, you have to consider the Service class rather than Task.
编辑:这应该适合您:
服务服务=新服务<>(任务);
//Updated use this to create a new Service object instead
Service service = new Service() {
@Override
protected Task createTask() {
return new Task() {
@Override
protected Void call() throws Exception {
//Your codes here
return null;
}
};
}
};
@FXML protected void launch(ActionEvent event){
if (!service.isRunning()) {
service.reset();
service.start();
}
}
这篇关于JavaFX:多次使用线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!