【发布时间】:2016-02-12 12:54:36
【问题描述】:
我已经尝试了一段时间了,
我正在尝试编写一个聊天服务器应用程序,只是为了学习。 我有一个我无法理解的障碍,
GUI 类内部的 while 循环冻结,但只是在它试图读取时:
public void run(){
Platform.runLater(() -> {
do {
try {
msg = getFromServer.readUTF(); // <--- freeze GUI
chatWindow.appendText(msg);
} catch (IOException e) {
e.printStackTrace();
}
} while (true);
});
}
你可以看到它在一个线程中运行,但我确实尝试以其他方式运行它...
只有 DataInputStream 会卡住,
msg = getFromServer.readUTF();
这就是它的来源:
public void connectToServer(){
try {
serverConectionState = new Socket("127.0.0.1", 6789);
getFromServer = new DataInputStream(serverConectionState.getInputStream());
sendToServer = new DataOutputStream(serverConectionState.getOutputStream());
onlineOffline.setText("Online");
onlineOffline.setTextFill(javafx.scene.paint.Color.web("#0076a3"));
} catch (IOException ex){
chatWindow.appendText("server connection fail\n");
}
}
这个类,是 Controller.class - 如果它有任何不同的话。
在社区的大力帮助下,我在 stackoverflow 中的第一个问题。
提前致谢
【问题讨论】:
-
如以下答案中所建议的那样,只有当您想要更新 UI 并且不在这些线程中执行业务逻辑或数据操作时,您才必须使用
Platform.runLater()。因此,在您的示例中,您应该调用Runnable,并且当可运行对象完成工作时,它应该使用Platform.runLater()更新 UI。另请注意,对于大型应用程序,最好使用 ExecutorService ,而不是按需生成线程
标签: java javafx connection-string fxml