sleep和wait可以響應中斷


sleep與wait區別:

1.sleep方法是線程靜態方法,wait方法是Object對象方法;

2.sleep使線程休眠,不會釋放鎖;wait方法是在獲取鎖情況下進行等待的,等待時會釋放鎖;

3.都可以響應中斷。

public class Test {

    static Object lock = new Object();
    
    public static void main(String[] args) {
        //休眠測試
        Thread t = new Thread(() -> {
            System.out.println("休眠");
            long s = System.currentTimeMillis();
            try {
                Thread.sleep(100000);
            } catch (InterruptedException e) {
                System.out.println("結束休眠2 " + (System.currentTimeMillis() - s));
            }
        });
        t.start();
        System.out.println("中斷休眠");
        t.interrupt();
        
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
        }
        
        //wait測試
        System.out.println("-----------wait---------");
        Thread t1 = new Thread(() -> {
            
            synchronized(lock) {
                System.out.println("等待");
                long s = System.currentTimeMillis();
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    System.out.println("結束wait1 " + (System.currentTimeMillis() - s));
                }
            }
            
            
        });
        t1.start();
        System.out.println("中斷wait");
        t1.interrupt();
    }

}

輸出:

中斷休眠
休眠
結束休眠2 0
-----------wait---------
中斷wait
等待
結束wait1 0

 


免責聲明!

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



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