嗯,我目前正在学习 JavaFX,作为一个完全的初学者(但不是 Java),我开始阅读 Java 的官方教程,我目前正在学习 Concurrency in JavaFX 。我尝试创建我的第一个 JavaFx Task
对象并启动它。这是我到目前为止所尝试过的
Task<Integer> task = new Task<Integer>(){
@Override protected Integer call() throws Exception{
int iterations;
for(iterations = 0; iterations < 10000; iterations++){
if(isCancelled()){
break;
}
System.out.println("Iteration " + iterations);
Thread.sleep(3000);
}
return iterations;
}
};
//start the background task
Thread th = new Thread(task);
th.setDaemon(true);
System.out.println("Starting background task...");
th.start();
System.out.println("Background task started...");
但是任务没有开始。我在控制台中没有看到任何消息。有什么我错过的吗?
最佳答案
任务应该在 JavaFX 应用程序的上下文中运行,如下例所示
import javafx.application.Application;
import javafx.concurrent.Task;
import javafx.stage.Stage;
import java.io.IOException;
public class JavaTaskClass extends Application{
public static void main(String[] args) {
launch(args);
}
@Override public void start(final Stage stage) throws IOException {
//create task object
Task<Integer> task = new Task<Integer>(){
@Override
protected Integer call() throws Exception{
System.out.println("Background task started...");
int iterations;
for(iterations = 0; iterations < 10000; iterations++){
if(isCancelled()){
break;
}
System.out.println("Iteration " + iterations);
Thread.sleep(3000);
}
return iterations;
}
};
//start the background task
Thread th = new Thread(task);
th.setDaemon(true);
System.out.println("Starting background task...");
th.start();
}
}
关于java - 无法使用 Thread.start() 启动 JavaFX 任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14116996/