1. 程式人生 > >SystemClock.sleep和Thread.sleep原始碼分析

SystemClock.sleep和Thread.sleep原始碼分析

一、在android中休眠3s鐘有2中方法:

1、SystemClock.sleep(3000);

2、Thread.sleep(3000);

二、通過系統原始碼區別

1、SystemClock.sleep(long ms)原始碼:

[java] view plain copy  print?
  1. publicstaticvoid sleep(long ms)  
  2.    {  
  3.        long start = uptimeMillis();  
  4.        long duration = ms;  
  5.        boolean interrupted = false;  
  6.        do {  
  7.            try {  
  8.               <span style="color:#ff0000;"> Thread.sleep(duration);</span>  
  9.            }  
  10.            catch (InterruptedException e) {  
  11.                interrupted = true;  
  12.            }  
  13.            duration = start + ms - uptimeMillis();  
  14.        } while (duration > 
    0);  
  15.        if (interrupted) {  
  16.            // Important: we don't want to quietly eat an interrupt() event,
  17.            // so we make sure to re-interrupt the thread so that the next
  18.            // call to Thread.sleep() or Object.wait() will be interrupted.
  19.            Thread.currentThread().interrupt();  
  20.        }  
  21.    }  
有原始碼可知SystemClock.sleep還是呼叫Thread.sleep [java] view plain copy  print?
  1. Thread.sleep(long time)原始碼:  
[java] view plain copy  print?
  1. publicstaticvoid sleep(long time) throws InterruptedException {  
  2.         Thread.sleep(time, 0);  
  3.     }  
[java] view plain copy  print?
  1. publicstaticvoid sleep(long millis, int nanos) throws InterruptedException {  
  2.       VMThread.sleep(millis, nanos);  
  3.   }  
[java] view plain copy  print?
  1. 最終呼叫到</span>VMThread類原始碼,再呼叫到底層  
[java] view plain copy  print?
  1. <pre name="code"class="java"staticnativevoid sleep (long msec, int nsec) throws InterruptedException;  

3、所以在android開發者建議使用Thread.sleep(long time)方法