try {
//thread to sleep for the specified number of milliseconds
Thread.sleep(100);
} catch ( java.lang.InterruptedException ie) {
System.out.println(ie);
}
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
Log.i(TAG, "I've waited for two hole seconds to show this!");
}
}, 2000);
public static void main(String[] args) throws InterruptedException {
//type code
short z=1000;
Thread.sleep(z);/*will provide 1 second delay. alter data type of z or value of z for longer delays required */
//type code
}
例如:-
class TypeCasting {
public static void main(String[] args) throws InterruptedException {
short f = 1;
int a = 123687889;
short b = 2;
long c = 4567;
long d=45;
short z=1000;
System.out.println("Value of a,b and c are\n" + a + "\n" + b + "\n" + c + "respectively");
c = a;
b = (short) c;
System.out.println("Typecasting...........");
Thread.sleep(z);
System.out.println("Value of B after Typecasting" + b);
System.out.println("Value of A is" + a);
}
}
public static void main(String[] args) {
//some code
long original = System.currentTimeMillis();
while (true) {
if (System.currentTimeMillis - original >= 5000) {
break;
}
}
//more code after waiting
}
import java.util.concurrent.TimeUnit;
public class DelaySample {
public static void main(String[] args) {
DelayUtil d = new DelayUtil();
System.out.println("started:"+ new Date());
d.delay(500);
System.out.println("half second after:"+ new Date());
d.delay(1, TimeUnit.MINUTES);
System.out.println("1 minute after:"+ new Date());
}
}
DelayUtil 实施:
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class DelayUtil {
/**
* Delays the current thread execution.
* The thread loses ownership of any monitors.
* Quits immediately if the thread is interrupted
*
* @param durationInMillis the time duration in milliseconds
*/
public void delay(final long durationInMillis) {
delay(durationInMillis, TimeUnit.MILLISECONDS);
}
/**
* @param duration the time duration in the given {@code sourceUnit}
* @param unit
*/
public void delay(final long duration, final TimeUnit unit) {
long currentTime = System.currentTimeMillis();
long deadline = currentTime+unit.toMillis(duration);
ReentrantLock lock = new ReentrantLock();
Condition waitCondition = lock.newCondition();
while ((deadline-currentTime)>0) {
try {
lock.lockInterruptibly();
waitCondition.await(deadline-currentTime, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
} finally {
lock.unlock();
}
currentTime = System.currentTimeMillis();
}
}
}
0
或者,如果您不想处理线程,请尝试以下方法:
public static void pause(int seconds){
Date start = new Date();
Date end = new Date();
while(end.getTime() - start.getTime() < seconds * 1000){
end = new Date();
}
}
13 回答
你面前有很多阅读 . 从编译器错误到异常处理,线程和线程中断 . 但这会做你想要的:
正如其他用户所说,你应该使用
try{...} catch{...}
块围绕你的通话 . 但是自从Java 1.5发布以来,有一个TimeUnit类和 Thread.sleep(millis) 一样,但更方便 . 您可以选择睡眠操作的时间单位 .它还有其他方法:TimeUnit Oracle Documentation
看看at this excellent brief post如何正确地做到这一点 .
基本上: grab InterruptedException . 请记住,您必须添加此catch-block . 该帖子进一步解释了这一点 .
使用以下编码结构来处理异常
将
Thread.sleep
放入try catch块中当使用 Android (我使用Java的唯一时间)时,我建议使用处理程序,而不是让线程进入休眠状态 .
参考:http://developer.android.com/reference/android/os/Handler.html
试试这个:
我为Java程序添加延迟的方法 .
这是针对顺序延迟的,但对于循环延迟,请参考Java Delay/Wait .
例如:-
一种更简单的等待方法是使用
System.currentTimeMillis()
,它返回自1970年1月1日午夜起的毫秒数 . 例如,等待5秒:这样,您就不必使用线程和异常 . 希望这可以帮助!
使用
java.util.concurrent.TimeUnit
:睡一秒钟或
睡一会儿 .
由于这是一个循环,这提出了一个固有的问题 - 漂移 . 每次你运行代码然后再睡觉时,你会每隔一秒就跑步一次 . 如果这是一个问题,请不要使用
sleep
.此外,
sleep
在控制方面不是很灵活 .为了每秒或延迟一秒运行任务,我会推荐[
ScheduledExecutorService
] [1]和[scheduleAtFixedRate
] [2]或[scheduleWithFixedDelay
] [3] .要每秒运行方法
myTask
(Java 8):Thread.sleep()
对初学者来说很简单,可能适合单元测试和概念证明 .但请 DO NOT 使用
sleep()
获取 生产环境 代码 . 最终sleep()
可能会伤害你 .多线程/多核java应用程序使用“线程等待”概念的最佳实践 . 等待释放线程持有的所有锁和监视器,这允许其他线程获取这些监视器并在线程安静地休眠时继续 .
下面的代码演示了该技术:
DelayUtil
实施:或者,如果您不想处理线程,请尝试以下方法:
它在您调用它时启动,并在经过秒数后结束 .