首页 文章

使用Thread.sleep(x)或wait()时出现异常

提问于
浏览
333

我试图延迟 - 或者让我睡觉 - 我的Java程序,但是发生了错误 .

我无法使用 Thread.sleep(x)wait() . 出现相同的错误消息:

未报告的异常java.lang.InterruptedException;必须被 grab 或宣布被抛出 .

在使用 Thread.sleep()wait() 方法之前是否需要执行任何步骤?

13 回答

  • 3

    你面前有很多阅读 . 从编译器错误到异常处理,线程和线程中断 . 但这会做你想要的:

    try {
        Thread.sleep(1000);                 //1000 milliseconds is one second.
    } catch(InterruptedException ex) {
        Thread.currentThread().interrupt();
    }
    
  • 29

    正如其他用户所说,你应该使用 try{...} catch{...} 块围绕你的通话 . 但是自从Java 1.5发布以来,有一个TimeUnit类和 Thread.sleep(millis) 一样,但更方便 . 您可以选择睡眠操作的时间单位 .

    try {
        TimeUnit.NANOSECONDS.sleep(100);
        TimeUnit.MICROSECONDS.sleep(100);
        TimeUnit.MILLISECONDS.sleep(100);
        TimeUnit.SECONDS.sleep(100);
        TimeUnit.MINUTES.sleep(100);
        TimeUnit.HOURS.sleep(100);
        TimeUnit.DAYS.sleep(100);
    } catch (InterruptedException e) {
        //Handle exception
    }
    

    它还有其他方法:TimeUnit Oracle Documentation

  • -2

    看看at this excellent brief post如何正确地做到这一点 .

    基本上: grab InterruptedException . 请记住,您必须添加此catch-block . 该帖子进一步解释了这一点 .

  • 3

    使用以下编码结构来处理异常

    try {
      Thread.sleep(1000);
    } catch (InterruptedException ie) {
        //Handle exception
    }
    
  • 7

    Thread.sleep 放入try catch块中

    try {
        //thread to sleep for the specified number of milliseconds
        Thread.sleep(100);
    } catch ( java.lang.InterruptedException ie) {
        System.out.println(ie);
    }
    
  • 0

    当使用 Android (我使用Java的唯一时间)时,我建议使用处理程序,而不是让线程进入休眠状态 .

    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);
    

    参考:http://developer.android.com/reference/android/os/Handler.html

  • 13

    试试这个:

    try{
    
        Thread.sleep(100);
    }catch(Exception e)
    {
       System.out.println("Exception caught");
    }
    
  • 195

    我为Java程序添加延迟的方法 .

    public void pause1(long sleeptime) {
        try {
            Thread.sleep(sleeptime);
        } catch (InterruptedException ex) {
            //ToCatchOrNot
        }
    }
    
    public void pause2(long sleeptime) {
        Object obj = new Object();
        if (sleeptime > 0) {
            synchronized (obj) {
                try {
                    obj.wait(sleeptime);
                } catch (InterruptedException ex) {
                    //ToCatchOrNot
                }
            }
        }
    }
    public void pause3(long sleeptime) {
        expectedtime = System.currentTimeMillis() + sleeptime;
        while (System.currentTimeMillis() < expectedtime) {
            //Empty Loop   
        }
    }
    

    这是针对顺序延迟的,但对于循环延迟,请参考Java Delay/Wait .

  • 3
    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);
    
    
      }
    }
    
  • 573

    一种更简单的等待方法是使用 System.currentTimeMillis() ,它返回自1970年1月1日午夜起的毫秒数 . 例如,等待5秒:

    public static void main(String[] args) {
        //some code
        long original = System.currentTimeMillis();
        while (true) {
            if (System.currentTimeMillis - original >= 5000) {
                break;
            }
        }
        //more code after waiting
    }
    

    这样,您就不必使用线程和异常 . 希望这可以帮助!

  • 8

    使用 java.util.concurrent.TimeUnit

    TimeUnit.SECONDS.sleep(1);
    

    睡一秒钟或

    TimeUnit.MINUTES.sleep(1);
    

    睡一会儿 .

    由于这是一个循环,这提出了一个固有的问题 - 漂移 . 每次你运行代码然后再睡觉时,你会每隔一秒就跑步一次 . 如果这是一个问题,请不要使用 sleep .

    此外, sleep 在控制方面不是很灵活 .

    为了每秒或延迟一秒运行任务,我会推荐[ ScheduledExecutorService ] [1]和[ scheduleAtFixedRate ] [2]或[ scheduleWithFixedDelay ] [3] .

    要每秒运行方法 myTask (Java 8):

    public static void main(String[] args) {
        final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
        executorService.scheduleAtFixedRate(App::myTask, 0, 1, TimeUnit.SECONDS);
    }
    
    private static void myTask() {
        System.out.println("Running");
    }
    
  • 0

    Thread.sleep() 对初学者来说很简单,可能适合单元测试和概念证明 .

    但请 DO NOT 使用 sleep() 获取 生产环境 代码 . 最终 sleep() 可能会伤害你 .

    多线程/多核java应用程序使用“线程等待”概念的最佳实践 . 等待释放线程持有的所有锁和监视器,这允许其他线程获取这些监视器并在线程安静地休眠时继续 .

    下面的代码演示了该技术:

    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();
        }
    }
    

    它在您调用它时启动,并在经过秒数后结束 .

相关问题