JavaFX和Future(并发)无法在Future构造中创建Stage

时间:2014-12-07 17:27:05

标签: java javafx javafx-8 future

我正在尝试在Stage中创建第二个JavaFX Application。需要在Stage内创建此Runnable,其中包含Future构造。

小SSCCE:

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import javafx.application.Application;
import javafx.stage.Stage;

public class Main extends Application {

    private ExecutorService executor;
    private Stage primaryStage;

    @Override
    public void start(Stage primaryStage) {
        this.primaryStage = primaryStage;
        executor = Executors.newFixedThreadPool(10);

        executor.submit(exec);


    }

    Runnable exec = new Runnable(){

        @Override
        public void run() {
            // TODO Auto-generated method stub
            Future<Boolean> future = executor.submit(new Callable<Boolean>(){

                @Override
                public Boolean call() throws Exception {
                    // TODO Auto-generated method stub
                    boolean ret = false;

                    System.out.println("is called");                    
                    Stage st = new Stage();
                    System.out.println("is not called");

                    return ret;
                }});
            boolean output;
            try {
                output = future.get();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                output = false;
            }
            if(output){

                System.out.println(true);
            }
        }};

    public static void main(String[] args) {
        launch(args);
    }
}

如您所见,在Future中,创建了新的Stage。创建System.out.println()之前的Stage已执行。但是创建后的System.out.println()没有被执行。

为什么在创建ApplicationStage会挂起?

1 个答案:

答案 0 :(得分:0)

根据JavaDocs for Stage

  

必须在JavaFX上构造和修改舞台对象   应用程序线程。

因此,您的代码将抛出IllegalStateException。您需要在FX应用程序线程上构建Stage