我今天看了几个小时的视频后遇到了麻烦。
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();
}
}
答案 0 :(得分:1)
请参阅文章了解实际细节:Concurrency in JavaFX | JavaFX 2 Tutorials and Documentation, JavaFX 2.1, Irina Fedortsova。
文章中的一些重要引用:
javafx.concurrent包概述
Java平台提供了一整套通过
java.util.concurrent
包提供的并发库。javafx.concurrent
包通过考虑JavaFX Application线程和GUI开发人员面临的其他约束来利用现有的API。
javafx.concurrent
包由Worker
接口和两个基本类Task
和Service
组成,两者都实现了Worker
接口。Worker
接口提供了对后台工作程序与UI通信有用的API。Task
类是java.util.concurrent.FutureTask
类的完全可观察的实现。Task
类使开发人员能够在JavaFX应用程序中实现异步任务。Service
类执行任务。
WorkerStateEvent
类指定每当Worker
实现的状态发生更改时发生的事件。Task
和Service
类都实现了EventTarget
接口,因此支持监听状态事件。
Task
类定义了一个无法重用的一次性对象。如果您需要可重用的Worker
对象,请使用Service
类。
可以通过以下方式之一启动任务:
通过以给定任务作为参数启动线程:
Thread th = new Thread(task); th.setDaemon(true); th.start();
使用ExecutorService API:
ExecutorService.submit(task);
希望这有帮助。