How to make a thread sleep for specific amount of time in java?

前端 未结 5 519
借酒劲吻你
借酒劲吻你 2021-02-07 16:15

I have a scenario where i want a thread to sleep for specific amount of time.

Code:

    public void run(){
        try{
            //do something
               


        
5条回答
  •  南方客
    南方客 (楼主)
    2021-02-07 17:17

    1. using Sleep in my experience is usually to compensate for bad timing somewhere else in the program, reconsider!
    2. try this:

      public void run(){
              try{
                  //do something
                  long before = System.currentTimeMillis();
                  Thread.sleep(3000);
                  //do something after waking up
              }catch(InterruptedException e){
                  long diff = System.currentTimeMillis()-before;
                  //this is approximation! exception handlers take time too....
                  if(diff < 3000)
                      //do something else, maybe go back to sleep.
                      // interrupted exception hit before the sleep time is completed.so how do i make my thread sleep for exactly 3 seconds?
              }
      }
      
    3. if you do not interrupt the sleep yourself, why would this thread be awoken ? is seems that you are doing something very wrong...

提交回复
热议问题