Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用JavaFX实现多线程_Java_Multithreading_Javafx 8 - Fatal编程技术网

如何使用JavaFX实现多线程

如何使用JavaFX实现多线程,java,multithreading,javafx-8,Java,Multithreading,Javafx 8,我正在创建一个JavaFX应用程序,我需要GUI与类中的其他一些代码交互,但是GUI和其他代码显然不能运行,除非我为它们运行不同的线程 public class Client extends Application { public static void main(String[] args){ launch(args); } @Override public void start(Stage primaryStage){ primaryStage.setTitle("Hell

我正在创建一个
JavaFX
应用程序,我需要GUI与类中的其他一些代码交互,但是GUI和其他代码显然不能运行,除非我为它们运行不同的
线程

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();
}
公共类客户端扩展应用程序{
公共静态void main(字符串[]args){
发射(args);
}
@凌驾
公共无效开始(阶段primaryStage){
setTitle(“你好,世界!”);
按钮btn=新按钮();
btn.setText(“运行客户端”);
btn.setOnAction(新的EventHandler(){
@凌驾
公共无效句柄(ActionEvent事件){
请尝试{runClient();}catch(异常e){System.out.println(“发生异常,服务器关闭”);}
}
});
StackPane root=新的StackPane();
root.getChildren().addAll(btn);
原始阶段。设置场景(新场景(根,500500));
primaryStage.show();
}
public void runClient()引发异常{
串句;
串句;
BufferedReader INFOROMUSER=新的BufferedReader(新的InputStreamReader(System.in));
套接字clientSocket=新套接字(“localhost”,6789);
DataOutputStream outToServer=新的DataOutputStream(clientSocket.getOutputStream());
BufferedReader INFOROMSERVER=新的BufferedReader(新的InputStreamReader(clientSocket.getInputStream());
语句=INFOROMUSER.readLine();
outToServer.writeBytes(句子+“\n”);
ModSession=INFOROMSERVER.readLine();
System.out.println(“来自服务器:”+ModSession);
clientSocket.close();
}

runClient()
是服务器的客户端。我需要GUI与客户端通信,但我无法创建一个新的
线程来同时运行这两个线程。

以下是我认为您需要的。您可以创建一个为您处理多线程的线程。然后使用execute()将任务提交给它。您可以在链接中阅读基础知识

当您想从FXThread外部执行一些UI操作时,只需调用:

Platform.runLater(一些可以通过GUI代码运行);

它在FXThread上运行

public class Client extends Application {
    //Create a ExecutorService threadpool
    ExecutorService threadPool = Executors.newWorkStealingPool();

    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 {
                    //submit a new task to the threadPool which will be executed on another thread.
                    threadPool.execute(new Runnable() {
                        @Override
                        public void run() {
                            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();

        //############# Run something in the FXThread #############\\
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                //do some UI stuff like updating labels
            }
        });
    }
}


为什么不能创建新线程?您可以创建任意多个线程,但最好使用
ExecutorService
;唯一的问题是所有GUI任务都应该在GUI线程上(请参阅平台#稍后运行)你能告诉我该怎么做吗?我不知道该怎么做。这是JavaFX软件设计的一个基本方面,因此,从阅读制造商提供的相关信息开始可能是一个好主意。否则你将永远无法理解其背后的概念。
Platform.runLater(() -> {
    //DO STUFF HERE
});
threadPool.execute(() -> {
    runClient();
});
btn.setOnAction(event -> {
    try {
        ...
    } catch(Exception e) {
        ...
    }
});