【发布时间】:2014-10-04 10:11:07
【问题描述】:
我是 Javafx 的新手,并使用它开发了一个 IDE。 JavaFX 面临的问题是我必须使用Platform.runLater() 来反映来自其他线程的GUI 变化。作为我正在开发的 IDE,我使用多个线程来保持最新信息,并且使用 Platform.runLater() 会使应用程序无响应。有时后台进程必须打印数百万行的输出,我认为当多个线程尝试执行相同操作时会导致问题。我尝试放置一个计数器,以便如果输出大于 250000 行,它将在 250000 行之后打印输出,否则在线程完成后立即打印,即使在这种情况下,如果两个或多个线程尝试执行 @987654324 @(还有其他线程创建带有复选框项目并反映实时值的树)应用程序挂起,但后台的所有内容都保持正常运行,甚至应用程序也不会抛出任何异常。在普通的 java swing 应用程序中,我没有遇到任何类似的问题。所以我正在寻求指导来解决这些问题。有人可以给我解决类似问题的专业提示吗? :)
应@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。
-
@jewelsea 新编辑,试图复制问题:)
-
@jewelsea 有什么建议吗? :)
标签: java multithreading java-8 javafx-8