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
原文地址:https://www.cnblogs.com/shuimuzhushui/p/12705743.html