Cannot start JavaFX Task using Thread.start()


Question

Well I am currently studying JavaFX and as a total beginner(but not in Java) I started reading the official tutorials in Java and I'm currently studying Concurrency in JavaFX. and I tried to create my first JavaFx Task Object and start it. This what I have tried so far

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...");

but the task doesn't start. I don't see any messages in my console. Is there something I missed?

1
1
1/2/2013 4:56:25 AM

Accepted Answer

Tasks are meant to be run in the context of a JavaFX application, like in the example below

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

}
2
1/2/2013 11:07:09 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon