Java Thread.sleep方法
阿新 • • 發佈:2018-12-07
1. Thread.sleep方法
sleep
方法掛起當前執行緒,直到一段時間後再次進入等待狀態。
public class ThreadSleep extends Thread { @Override public void run() { System.out.println("ThreadSleep begin " + System.currentTimeMillis()); try { Thread.sleep(1000); } catch (InterruptedException e) { } System.out.println("ThreadSleep end " + System.currentTimeMillis()); } public static void main(String[] args) { new ThreadSleep().start(); } }
輸出
ThreadSleep begin 1543818092774
ThreadSleep end 1543818093774
2. sleep方法與鎖物件
sleep()
方法並不會放棄鎖物件。
public class ThreadSleepLock extends Thread { Object lock; public ThreadSleepLock(Object lock) { this.lock = lock; } @Override public void run() { synchronized (lock) { System.out.println("ThreadSleepLock begin " + System.currentTimeMillis()); try { Thread.sleep(2000); } catch (InterruptedException e) { } System.out.println("ThreadSleepLock end " + System.currentTimeMillis()); } } public static void main(String[] args) { Object lock = new Object(); new ThreadSleepLock(lock).start(); try { Thread.sleep(100); } catch (InterruptedException e) { } synchronized (lock) { System.out.println("main end " + System.currentTimeMillis()); } } }
輸出
ThreadSleepLock begin 1543818504341
ThreadSleepLock end 1543818506341
main end 1543818506341
3. sleep方法與interrupt方法
如果執行緒在掛起狀態,呼叫執行緒的interrupt
方法會發生InterruptedException
異常。
public class ThreadSleepInterrupt extends Thread { @Override public void run() { System.out.println("ThreadSleepInterrupt begin " + System.currentTimeMillis()); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("ThreadSleepInterrupt end " + System.currentTimeMillis()); } public static void main(String[] args) { Thread t = new ThreadSleepInterrupt(); t.start(); try { Thread.sleep(100); } catch (InterruptedException e) { } t.interrupt(); } }
輸出
ThreadSleepInterrupt begin 1543818907713
java.lang.InterruptedException: sleep interrupted
ThreadSleepInterrupt end 1543818907814
at java.lang.Thread.sleep(Native Method)
at com.blog.demo.thread.ThreadSleepInterrupt.run(ThreadSleepInterrupt.java:9)
相關文章
Java Thread.join方法
Java Thread.sleep方法
Java Thread.Interrupt方法