gpt4 book ai didi

JavaFX : Use a Thread more than once

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:55:00 26 4
gpt4 key购买 nike

我是 JavaFX 的新手,线程有点问题:我可以执行它两次,但找不到原因。

这是我的代码的总结:

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();
}

当我第一次点击启动线程的按钮时,我的任务运行没有任何问题(我的控制台显示“开始!”和“成功”)。

但是,如果我第二次单击,则不会添加任何内容。难道我做错了什么 ?我们不能多次使用一个线程吗?

最佳答案

来自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.

来自Concurrency in JavaFX教程:

The Task class defines a one-time object that cannot be reused. If you need a reusable Worker object, use the Service class.

因此,您必须考虑 Service类而不是 Task .


编辑:这应该适合您:

Service service = new Service<>(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 : Use a Thread more than once,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16037062/

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