3 回答

TA貢獻(xiàn)1943條經(jīng)驗 獲得超7個贊
JAVA中使用延遲主要有以下兩種方法:
1、使用Timer類
Timer類的schedule方法可以按照時間計劃執(zhí)行程序。
public static void main(String[] args) {
Timer timer = new Timer();
TimerTask timerTask = new MyTimerTask();
timer.schedule(timerTask, 10000, 10000);
}
schedule方法中需要傳入一個TimerTask類型的對象,該對象需要繼承并實(shí)現(xiàn)TimerTask類的run方法,或者以匿名內(nèi)部類的方式實(shí)現(xiàn)run方法。schedule的第二個參數(shù)為程序第一次執(zhí)行run方法的延時時間,第三個參數(shù)為執(zhí)行完第一次run方法后延時循環(huán)執(zhí)行run方法的時間。例如,上面的程序就是延時10s執(zhí)行timerTask的run方法,執(zhí)行完畢之后每隔10s執(zhí)行一次run方法。
實(shí)現(xiàn)了run方法后就會根據(jù)schedule設(shè)置的時間計劃來執(zhí)行。schedule的參數(shù)也可以不要循環(huán)時間,只延時執(zhí)行一次,還有多種重載的schedule方法,可以根據(jù)實(shí)際情況使用。
2、使用Thread
Thread.currentThread().sleep(10000);
使線程暫停一段時間。

TA貢獻(xiàn)1802條經(jīng)驗 獲得超5個贊
Java中主要有兩種方法來實(shí)現(xiàn)延遲,即:Thread和Timer
1、普通延時用Thread.sleep(int)方法,這很簡單。它將當(dāng)前線程掛起指定的毫秒數(shù)。如
try
{
Thread.currentThread().sleep(1000);//毫秒
}
catch(Exception e){}
在這里需要解釋一下線程沉睡的時間。sleep()方法并不能夠讓程序"嚴(yán)格"的沉睡指定的時間。例如當(dāng)使用5000作為sleep()方法的參數(shù)時,線 程可能在實(shí)際被掛起5000.001毫秒后才會繼續(xù)運(yùn)行。當(dāng)然,對于一般的應(yīng)用程序來說,sleep()方法對時間控制的精度足夠了。
2、但是如果要使用精確延時,最好使用Timer類:
Timer timer=new Timer();//實(shí)例化Timer類
timer.schedule(new TimerTask(){
public void run(){
System.out.println("退出");
this.cancel();}},500);//五百毫秒
這種延時比sleep精確。上述延時方法只運(yùn)行一次,如果需要運(yùn)行多次, 使用timer.schedule(new MyTask(), 1000, 2000); 則每間隔2秒執(zhí)行MyTask()

TA貢獻(xiàn)1846條經(jīng)驗 獲得超7個贊
用Thread就不會iu無法終止
new Thread(new Runnable() {
public void run() {
while(true) {
repaint();
Thread.sleep(500);
}
}
}.start();
或者用現(xiàn)成的
javax.swing.Timer timer = new javax.swing.Timer(500, new ActionListener() {
public void actionPerformed(ActionEvent e) {
repaint();
}
};
timer.start();
添加回答
舉報