[英]Timer won't stop when there is a Thread.sleep inside Java
您好,我有這段代碼來使用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);
}
圖像將正確顯示,但當屏幕上出現圖像編號54時,它將循環返回1,這是因為
Thread.sleep(200);
我該如何解決? 我想延遲圖像之間的時間
這沒有任何意義。
這樣您將獲得:
因此,您將獲得大約十或十一個任務的迭代,大部分是並行的。
我建議你:
以200ms的間隔安排任務,使每次調用時都顯示下一個順序圖像,環繞到開始處或取消計時器,或者在到達最后一個圖像時進行所需的任何操作,以及
擺脫內部循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.