JavaFX后台线程出现问题

时间:2017-08-15 20:48:01

标签: java multithreading javafx

我今天看了几个小时的视频后遇到了麻烦。

Executer service,worker,task,concurrent package ... ??我很困惑在哪里做什么。

我想初始化几个在启动时将消息发布到UI的对象。

我有一个界面:

<script src="../js/pikaday-responsive-modernizr.js"></script>

我的一个对象和一些方法

public interface SystemMessage {
    void postMessage(String outText);
}

我的主文件,在启动时初始化多个对象。

public class Identity extends Service {
    private String machineId = null;

    private static SystemMessage systemMessage;

    public Identity(SystemMessage smInterface){
        systemMessage = smInterface;

        //how do i run the identity class in the background and report to the UI?
        // --------------------------------------------------
        //
        systemMessage.postMessage("Checking Machine Identity");
        if (getStoredIdentity()){
            systemMessage.postMessage("Machine ID exists.");
        }
        else{
            systemMessage.postMessage("No Machine ID. Create New.");
            machineId = createUuid();
            storeIdentity();
        }
    }
}

// --------------------------------------------------
//
//Do I create individual tasks for each method in the class? do i use service, task, executer, or????
// --------------------------------------------------
//

private void storeIdentity(){
    Properties p = new Properties();
    p.setProperty("machineId", this.machineId);
    try {
        FileWriter file = new FileWriter("identity.properties");
        p.store(file, "Identity");
        systemMessage.postMessage("New Identity Created and Stored.");
    } catch (IOException e) {
        systemMessage.postMessage("Error Creating New Identity!");
        e.printStackTrace();
    }
}

1 个答案:

答案 0 :(得分:1)

请参阅文章了解实际细节:Concurrency in JavaFX | JavaFX 2 Tutorials and Documentation, JavaFX 2.1, Irina Fedortsova

文章中的一些重要引用:

  1.   

    javafx.concurrent包概述

         

    Java平台提供了一整套通过java.util.concurrent包提供的并发库。 javafx.concurrent包通过考虑JavaFX Application线程和GUI开发人员面临的其他约束来利用现有的API。

         

    javafx.concurrent包由Worker接口和两个基本类TaskService组成,两者都实现了Worker接口。 Worker接口提供了对后台工作程序与UI通信有用的API。 Task类是java.util.concurrent.FutureTask类的完全可观察的实现。 Task类使开发人员能够在JavaFX应用程序中实现异步任务。 Service类执行任务。

         

    WorkerStateEvent类指定每当Worker实现的状态发生更改时发生的事件。 TaskService类都实现了EventTarget接口,因此支持监听状态事件。

  2.   

    Task类定义了一个无法重用的一次性对象。如果您需要可重用的Worker对象,请使用Service类。

  3.   

    可以通过以下方式之一启动任务:

         
        
    • 通过以给定任务作为参数启动线程:

      Thread th = new Thread(task);
      th.setDaemon(true);
      th.start();
      
    •   
    • 使用ExecutorService API:

      ExecutorService.submit(task);
      
    •   
  4. 希望这有帮助。