在Java中有時(shí)候需要使程序暫停一點(diǎn)時(shí)間,稱為延時(shí)。普通延時(shí)用Thread.sleep(int)方法,這很簡(jiǎn)單。它將當(dāng)前線程掛起指定的毫秒數(shù)。如
Java 代碼復(fù)制內(nèi)容到剪貼板
- try
- {
- Thread.currentThread().sleep(1000);//毫秒
- }
- catch(Exception e){}
在這里需要解釋一下線程沉睡的時(shí)間。sleep()方法并不能夠讓程序"嚴(yán)格"的沉睡指定的時(shí)間。例如當(dāng)使用5000作為sleep()方法的參數(shù)時(shí),線 程可能在實(shí)際被掛起5000.001毫秒后才會(huì)繼續(xù)運(yùn)行。當(dāng)然,對(duì)于一般的應(yīng)用程序來說,sleep()方法對(duì)時(shí)間控制的精度足夠了。
但是如果要使用精確延時(shí),最好使用Timer類:
Java 代碼復(fù)制內(nèi)容到剪貼板
- Timer timer=new Timer();
- timer.schedule(new TimerTask(){
- public void run(){
- System.out.println("退出");
- this.cancel();}},500);
這種延時(shí)比sleep精確。上述延時(shí)方法只運(yùn)行一次,
如果需要運(yùn)行多次, 使用timer.schedule(new MyTask(), 1000, 2000); 則每間隔2秒執(zhí)行MyTask()