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

前端 未结 5 517
借酒劲吻你
借酒劲吻你 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

    When your thread is hit by an interrupt it will go into the InterruptedException catch block. You can then check how much time the thread has spent sleeping and work out how much more time there is to sleep. Finally, instead of swallowing the exception, it is good practice to restore the interruption status so that code higher up the call stack can deal with it.

    public void run(){
    
        //do something
    
        //sleep for 3000ms (approx)     
        long timeToSleep = 3000;
        long start, end, slept;
        boolean interrupted;
    
        while(timeToSleep > 0){
            start=System.currentTimeMillis();
            try{
                Thread.sleep(timeToSleep);
                break;
            }
            catch(InterruptedException e){
    
                //work out how much more time to sleep for
                end=System.currentTimeMillis();
                slept=end-start;
                timeToSleep-=slept;
                interrupted=true
            }
        }
    
        if(interrupted){
            //restore interruption before exit
            Thread.currentThread().interrupt();
        }
    }
    

提交回复
热议问题