简体   繁体   中英

Timer won't stop when there is a Thread.sleep inside Java

Hello i have this code to display images with javafx

public  void CantaCarta() throws InterruptedException {
            startGame.setDisable(true);
                Timer timer = new Timer();
            timer.scheduleAtFixedRate(new TimerTask() {
                @Override
                public void run() {
                    SwingUtilities.invokeLater(() -> {
                        for (int x=1; x<55;x++){

                            Image image = new Image(getClass().getResource("imgs/"+JuegoLoto.Muestra(x-1)+".jpg").toString(), true);
                            cantada.setImage(image);
                            if (x >= 54) {
                                System.out.print("Termina");
                                timer.cancel();
                            }  else {
                                System.out.print(" "+x+" ");

                                try {
                                    Thread.sleep(200);
                                } catch (InterruptedException ex) {
                                }
                            }


                        }
                    });
                }
            }, 0, 1000);

     }

The images will displa correctly but when the image number 54 is in the screen it will be back to 1 in a loop all because of this

 Thread.sleep(200);

How can i solve this? i want to delay the time beetween images

This doesn't begin to make sense.

  • You're scheduling a timer task to run every 1000 milliseconds.
  • The task has 54 internal iterations which each display an image and in all cases except the last sleep for 200ms.
  • Total time so far 10600 milliseconds plus however long it takes to display the images
  • The timer will reschedule the task after 1000ms of that: meanwhile
  • the task will cancel the timer on the last iteration.

So you will get:

  • 53 images and 53 200ms sleeps
  • a restart of the task after about 10% of that is complete
  • a 54th image
  • the timer gets cancelled.

So you get about ten or eleven iterations of the task, mostly in parallel.

I suggest you:

  • schedule the task at 200ms intervals, have it display the next sequential image every time it is invok d, wrapping around to the beginning or cancelling the timer or whatever you want when it gets to the last image, and

  • get rid of the internal loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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