我是Javafx的新手,並使用它開發IDE。 JavaFX面臨的問題是,我必須使用Platform.runLater()
來反映來自其他線程的GUI變化。由於我正在開發的IDE使用多線程來保持最新信息,並使用Platform.runLater()
使應用程序無響應。有時後臺進程必須打印出數百萬行的輸出,我認爲在多個線程嘗試執行相同操作時會導致問題。我試圖放一個計數器,這樣如果輸出大於250000行,它將在250000行之後打印輸出,否則在線程完成後會立即打印輸出,即使在這種情況下,如果兩個或多個線程試圖執行Platform.runLater()
(還有其他線程會創建帶有複選框項目的樹並反映實時值)應用程序掛起,但後臺中的所有內容都保持正常運行,甚至應用程序不會拋出任何異常。在正常的java swing應用程序中,我沒有遇到類似的問題。所以我正在尋求指導來解決這些問題。有人可以給我PRO提示來解決類似問題嗎? :)開發多線程Javafx應用程序時需要注意哪些事項?
編輯在@jewelsea的請求
我試圖保持示例代碼儘可能簡單
FxUI.java
public class FxUI extends Application {
public static TextArea outputArea;
@Override
public void start(Stage primaryStage) {
outputArea= new TextArea();
Button btn = new Button();
btn.setText("Start Appending Text To Text Area");
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Thread r=new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
Thread t= new Thread(new simpleThread(i));
t.start();
try {
Thread.sleep(1000);
System.out.println("Thread Awake");
} catch (InterruptedException ex) {
Logger.getLogger(FxUI.class.getName()).log(Level.SEVERE, null, ex);
}
} }
});
r.start();
}
});
VBox root = new VBox(30);
outputArea.setWrapText(true);
outputArea.setPrefHeight(400);
root.getChildren().add(outputArea);
root.getChildren().add(btn);
Scene scene = new Scene(root, 500, 500);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
simpleThread.java
public class simpleThread implements Runnable {
int threadnumber;
public simpleThread(int j) {
threadnumber = j;
}
@Override
public void run() {
String output = "";
String content;
int length;
final String finalcontent2;
final int finallength2;
for (long i = 0L; i <= 10000; i++) {
final String finalcontent;
final int finallength;
if (i % 1000 == 0) {
output += "\nThread number = " + threadnumber + " \t Loop Counter=" + i;
content = FxUI.outputArea.getText() + "\n" + output;
length = content.length();
finallength = length;
finalcontent = "" + content;
Platform.runLater(new Runnable() {
@Override
public void run() {
System.out.println("appending output");
FxUI.outputArea.setText(finalcontent);
FxUI.outputArea.positionCaret(finallength);
}
});
} else {
output += "\nThread number = " + threadnumber + " \t Loop Counter=" + i;
}
System.out.println("Thread number = " + threadnumber + " \t Loop Counter=" + i);
}
}
}
您應該提供[mcve](http://stackoverflow.com/help/mcve)。 – jewelsea 2014-10-04 16:29:51
@jewelsea新的編輯,試圖複製的問題:) – DeepSidhu1313 2014-10-04 18:33:54
@jewelsea任何建議? :) – DeepSidhu1313 2014-10-05 18:39:46