我正在创建一个 JavaFX
应用程序,我需要GUI与类中的一些其他代码进行交互,但显然GUI和其他代码块不能在同一个线程上运行,因此我需要为它们分别创建不同的 Thread
。
public class Client extends Application {
public static void main(String[] args){
launch(args);
}
@Override
public void start(Stage primaryStage){
primaryStage.setTitle("Hello world!");
Button btn = new Button();
btn.setText("Run Client");
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
try{runClient();}catch (Exception e){System.out.println("Exception Occurred, Server is down.");}
}
});
StackPane root = new StackPane();
root.getChildren().addAll(btn);
primaryStage.setScene(new Scene(root, 500, 500));
primaryStage.show();
}
public void runClient() throws Exception {
String sentence;
String modSentence;
BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 6789);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + "\n");
modSentence = inFromServer.readLine();
System.out.println("From Server: " + modSentence);
clientSocket.close();
}
runClient()
是客户端,需要GUI与客户端通讯,但是我无法创建一个新的Thread
来同时运行它们。
ExecutorService
;唯一需要注意的是所有GUI任务都应该在GUI线程上执行(请参见Platform#runLater)。 - fge