Object 中的wait和Thread中sleep的区别

https://www.cnblogs.com/hongten/p/hongten_java_sleep_wait.html

一、区别

1、wait()来自于Object类而sleep来自于Thread类

2、sleep没有释放锁,但是wait释放了锁(使得其他线程可以使用同步控制块或者方法锁)

3、wait,notify和notifyAll只能在同步控制方法或者同步控制块使用,而sleep能在各个地方使用

4、sleep必须捕获异常,但是其它wait不用

5、sleep让一个线程睡眠,等待一段时间后,自动醒来进入可运行状态,不会马上进入运行状态,因为线程调度机制恢复线程也需要时间。如果调用interrup方法,则会抛出InterruptedException。如果不捕获这个异常,那么会进入TERMINATED状态。如果捕获这个异常,那么可以在catch中继续执行后面的代码。

6、sleep是静态方法,只会让当前线程sleep,t.sleep()并不会让t进入sleep

 

 

如果线程并不处于wait,sleep,join状态时,调用interrupt方法线程不会抛出InterruptedException。

wait和notify必须在synchronized方法或者block中。

 

二、Code便于理解

package threads.waitandsleep;

/**
 * Created by adrian.wu on 2019/6/1.
 */
public class TestD {
    public static void main(String[] args) {
        new Thread(new Thread1()).start();

        try {
            Thread.sleep(5000);
        }catch (Exception e){
            e.printStackTrace();
        }
        new Thread(new Thread2()).start();
    }

    public static class Thread1 implements Runnable {
        @Override
        public void run() {
            synchronized (TestD.class) {
                System.out.println("enter thread1....");
                System.out.println("thread1 is waiting");
                try {
                    TestD.class.wait();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            System.out.println("thread1 is going on....");
            System.out.println("thread1 is over!!");
        }
    }

    public static class Thread2 implements Runnable {
        @Override
        public void run() {
            synchronized (TestD.class) {
                System.out.println("enter thread2....");
                System.out.println("thread2 is waiting");

                TestD.class.notify();
            }

            try {
                Thread.sleep(5000);
            }catch (Exception e){
                e.printStackTrace();
            }
            System.out.println("thread2 is going on....");
            System.out.println("thread2 is over!!");
        }
    }
}

 

 

结果:

enter thread1....
thread1 is waiting
enter thread2....
thread2 is waiting
thread1 is going on....
thread1 is over!!
thread2 is going on....
thread2 is over!!

 

解释:

wait()会释放锁,sleep()不会。也就是说wait 需要notify去唤醒。而sleep()并不会。只要当sleep时间到了就会自动执行下面的过程,但是会让出CPU线程。

 

转载于:https://www.cnblogs.com/ylxn/p/10395315.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值