JavaFX : Use a Thread more than once

前端 未结 3 2313
天命终不由人
天命终不由人 2021-02-20 14:38

I\'m new with JavaFX and I\'ve a little problem with a thread: I can execute it twice and I can\'t find why.

Here is a sum-upt of my code:

Task

        
3条回答
  •  你的背包
    2021-02-20 15:20

    Do it with a wraper class

                import java.io.IOException;
                import javafx.concurrent.Task;
    
                public class Executor {
                    private String name;
                    private Task task;
    
                    public Executor(final String name) {
                        this.name=name;
                        task = new Task() {
                            @Override
                            public Void call() throws IOException, InterruptedException {
                                try {
                                    int i=0;
                                    while(i<20){
                                        System.out.println(name);
                                        Thread.sleep(2000);
                                        i++;
                                    }
                                    return null;
                                } catch (IllegalThreadStateException e) {
                                    System.out.println(e);
                                }
                                return null;
                            }
    
                            @Override
                            protected void succeeded() {
                                super.succeeded();
                                try {
                                    System.out.println(name+"  finish");
                                } catch (Exception ex) {
                                    System.out.println(ex);
                                }
                            }
                        };
                    }
    
                    public void start() {
                        try {
                                    Thread th = new Thread(task);
                                    th.start();
                                } catch (Exception ex) {
                                    System.out.println(ex);
                                }
                    }
                }
    

提交回复
热议问题