简体   繁体   English

带有Task的Java中的多线程仅在onClick Button上起作用一次

[英]Multi threading in Java with Task only work once when onClick Button

Attached is the code snippet below. 随附的代码段如下。 I am new to multi-threading. 我是多线程新手。 Attempted to do multi threading which sort of works. 尝试做多线程哪种工作。 However, after I click the button the first time, the second time onwards would not "create the thread" and run my method anymore. 但是,第一次单击按钮后,第二次以后将不再“创建线程”并运行我的方法。

I have also experimented with implementing the Runnable interface, but it could not get my Anchorpane reference to load the snackbar and hence I used the task method instead. 我也尝试过实现Runnable接口,但是无法获得我的Anchorpane参考来加载小吃栏,因此我改用task方法。 Appreciate your help! 感谢您的帮助!

    @FXML
    private AnchorPane anchorPane;

    Thread thread;
    @FXML
    void onClickLoginButton(ActionEvent event) throws Exception {
            thread = new Thread(task);
            thread.start();
    }
    Task<Void> task = new Task<Void>() {
        @Override
        public Void call(){
            //System.out.println("Thread running"+thread.getId());
            try {
                credential = login.login();
            } catch (UnknownHostException u) {
                Platform.runLater(() -> {
                    System.out.println("No wifi");
                    JFXSnackbar snackbar = new JFXSnackbar(anchorPane);
                    snackbar.show("Please check your internet connection", 3000);
                    //u.printStackTrace();
                });
            } catch (Exception e) {
                //e.printStackTrace();
            }
            //System.out.println("Thread running"+thread.getId());
            return null;
        }
    };

The reason why this runs only once has to do with how Task works in general 它只运行一次的原因与Task的总体工作方式有关

Per Task 's documentation here: https://docs.oracle.com/javase/8/javafx/api/javafx/concurrent/Task.html 每个Task的文档在这里: https : //docs.oracle.com/javase/8/javafx/api/javafx/concurrent/Task.html

As with FutureTask, a Task is a one-shot class and cannot be reused. 与FutureTask一样,Task是单发类,不能重用。 See Service for a reusable Worker. 请参阅服务以获取可重复使用的工作人员。

Thus, if you want to repeat the said process multiple times, using a Task is not a good choice. 因此,如果您想重复上述过程多次,使用Task并不是一个好的选择。 Check the recommended alternatives for workers and services in you want to achieve something like that. 检查您想要实现类似目标的工作人员和服务的推荐替代方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM