多線程中sleep方法,簡單介紹。


一 是什么?

package com.aaa.threaddemo;
/*
 * 多線程中的sleep方法? 
 *         sleep 隸屬於Thread的方法,顧名思義,讓線程睡一會。
             1 public static native void sleep(long millis) throws InterruptedException; 使用需要try catch,或者  聲明一個異常,才能使用。
             2    long 跟的時間單位是秒          
             3    會讓線程進入阻塞狀態
             4 調用線程會【暫時讓出指定時間】的執行權。讓出CPU,但是監控狀態依然保持着。
             5 線程不會釋放對象鎖。
             6 如果在睡眠期間其他線程調用了該線程的interrupt()方法中斷了該線程,則該線程會在調用sleep方法的地方拋出InterruptedException異常而返回。
 */
public class ThreadRun {
    public static void main(String[] args) throws InterruptedException {
        Thread1 thread1 = new Thread1();
        thread1.start();
        //在thread1 阻塞的情況下,讓其中斷,會拋出異常          java.lang.InterruptedException
        thread1.interrupt();        
    }
}

class Thread1 extends Thread{
    @Override
    public void run() {    
        try {
            System.out.println("1111");        
            // 讓子線程休息一秒, 在一秒內線程讓出CPU,此時thread1 進入阻塞狀態。
            // 一秒后函數正常返回,參與CPU的調度。獲取到CPU資源進入到運行狀態。
            Thread1.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

 

 

 

 

二 驗證sleep,監控狀態依然保持。      原文 https://zhuanlan.zhihu.com/p/259158177

package com.aaa.threaddemo; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /* * 多線程中的sleep方法? * sleep 隸屬於Thread的方法,顧名思義,讓線程睡一會。 1 public static native void sleep(long millis) throws InterruptedException; 使用需要try catch,或者 聲明一個異常,才能使用。 2 long 跟的時間單位是秒 3 會讓線程進入阻塞狀態 4 調用線程會【暫時讓出指定時間】的執行權。讓出CPU,但是監控狀態依然保持着。 5 線程不會釋放對象鎖。 6 如果在睡眠期間其他線程調用了該線程的interrupt()方法中斷了該線程,則該線程會在調用sleep方法的地方拋出InterruptedException異常而返回。 */
public class ThreadRun { private static ReentrantLock lock = new ReentrantLock(); public static void main(String[] args) throws InterruptedException { Thread thread1 =  new Thread(new Runnable() { public void run() { //創建獨占鎖 
 lock.lock(); try { System.out.println("線程1開始睡覺"); Thread.sleep(1000); System.out.println("線程1結束睡覺"); } catch (InterruptedException e) { e.printStackTrace(); }finally { //解除鎖
 lock.unlock(); } } }); Thread thread2 =  new Thread(new Runnable() { public void run() { //創建獨占鎖
 lock.lock(); try { System.out.println("線程2開始睡覺"); Thread.sleep(2000); System.out.println("線程2結束睡覺"); } catch (InterruptedException e) { e.printStackTrace(); }finally { lock.unlock(); } } }); thread1.start(); thread2.start(); } }

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM