两个 Javafx 线程并不独立运行

问题描述 投票:0回答:1

我创建了两个标准线程(

Thread
类),每个线程都使用
Platform.runLater(...)
方法封装了一个 JavaFX 线程。 到那时两个java线程就被正确创建了。 然后我使用每个线程的
start()
方法启动两个线程。在调试模式下,我可以看到两个线程分别启动。 问题是两个 JavaFX 线程似乎不是独立的,因为在我的程序中,第二个 JavaFX 线程等待第一个线程完成才能启动。

我一定缺少一些关于 FX 线程的信息,因为我已经在标准 java 中创建了并且从未遇到过此类问题。

非常感谢您的帮助和解答。

每个 FX 线程在不同的

Task
上工作。 第一个
Task
计算,第二个
Task
每秒在
Label
中显示进度百分比。

public void init() {
    computetask = new Task<Void>() {
   
    @Override
    public Void call() {
        //----Future Use--------------------------------------
        // The folowing commented method takes approximately
        // 30 to 40 minutes and generates 10 million lines
        // in the history table for a period of 20 years.
        // For the moment and the time to resolve the 
        // non-concurrent thread problem the program only does 
        // basic counting.
        //----------------------------------------
        //spe.computeStoksEvolution(labelmessage);
       //--------------------------------------------------
        double total = 100.;
        current = 0;

        while(current <= total) {
            percent = ((current/total) * 100.);
            current += 1.;
            System.out.println("Incremental loop: " + percent);
        }

        stockssynthesisui.labelmessage.setTextFill(Color.BLUE);
        stockssynthesisui.labelmessage.setText("Frequencies Computing ended.");
        stockssynthesisui.buttonfrequency.setDisable(false);

        return null;
    }

    printpecentingtask = new Task<Void>() {
        @Override
        protected Void call() throws Exception {
           int count = 0;

           //while(percent <= 100.) {
           for(count=1; count <= 5; count++) {
               percenttext = String.format("%03.06f", percent);
               stockssynthesisui.labelmessage.setText(percenttext);

               System.out.println(percenttext + " %");

               Thread.sleep(1000);
           }

           return null;
        }
    };

    System.out.println("run percenting");

    Thread t1 = new Thread( () -> {
        Platform.runLater(printpecentingtask);
    });

    System.out.println("run computing");

    Thread t2 = new Thread( () -> {
        Platform.runLater(computetask);
    });

    t1.start();
    t2.start();

    System.out.println("Both thread are stated");
}
multithreading javafx platform
1个回答
0
投票

只有一个JavaFX应用程序线程并且您不创建它,它是由JavaFX平台在启动时创建的。您只是创建自己的线程,它们不是“JavaFX 线程”。

您的问题是您稍后将在单个 JavaFX 线程上运行线程中的所有内容。因此,您的线程毫无意义,所有内容都在 JavaFX 应用程序线程上按顺序运行,包括循环和睡眠语句,这会完全冻结您的 UI。

© www.soinside.com 2019 - 2024. All rights reserved.