我正在学习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...");
但任务没有开始。我的控制台中没有看到任何消息。有没有我错过的东西?
答案 0 :(得分:2)
任务意味着在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();
}
}