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

前端 未结 5 910
盖世英雄少女心
盖世英雄少女心 2021-02-07 16:19

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:11

    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...

提交回复
热议问题