Java:为什么在Thread的run()方法中不能使用sleep()暂停线程呢?

2025-02-23 18:46:44
推荐回答(2个)
回答1:

sleep方法需要抛出异常

public static native void sleep(long millis) throws InterruptedException;

所以你需要try-catch一下才可以通过编译,你的code改为:

if (!flag) {
try{
    Thread.sleep(2000);
}catch(InterruptedException e){
    e.printStackTrace();
}
//剩下的代码

应该就可以了

回答2:

try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}