sleep() 和 wait() 有什么区别

sleep() 和 wait() 有什么区别?

  • sleep() 是 Thread 类的静态本地方法;wait() 是Object类的成员本地方法
  • sleep() 方法可以在任何地方使用;wait() 方法则只能在同步方法或同步代码块中使用,否则抛出异常Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
  • sleep() 会休眠当前线程指定时间,释放 CPU 资源,不释放对象锁,休眠时间到自动苏醒继续执行;wait() 方法放弃持有的对象锁,进入等待队列,当该对象被调用 notify() / notifyAll() 方法后才有机会竞争获取对象锁,进入运行状态
  • JDK1.8 sleep() wait() 均需要捕获 InterruptedException 异常

测试代码

public class TestWaitSleep {

	private static Object obj = new Object();
	
	public static void main(String[] args) {
		
		//测试sleep()
		//测试 RunnableImpl1 wait(); RunnableImpl2 notify()
		Thread t1 = new Thread(new RunnableImpl1(obj));
		Thread t2 = new Thread(new RunnableImpl2(obj));
		t1.start();
		t2.start();
		
		//测试RunnableImpl3 wait(long timeout)方法
		Thread t3 = new Thread(new RunnableImpl3(obj));
		t3.start();
	}

	
}

class RunnableImpl1 implements Runnable {

	private Object obj;
	
	public RunnableImpl1(Object obj) {
		this.obj = obj;
	}
	
	public void run() {
		System.out.println("run on RunnableImpl1");
		synchronized (obj) {
			System.out.println("obj to wait on RunnableImpl1");
			try {
				obj.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("obj continue to run on RunnableImpl1");
		}
	}
}

class RunnableImpl2 implements Runnable {

	private Object obj;
	
	public RunnableImpl2(Object obj) {
		this.obj = obj;
	}
	
	public void run() {
		System.out.println("run on RunnableImpl2");
		System.out.println("睡眠3秒...");
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		synchronized (obj) {
			System.out.println("notify obj on RunnableImpl2");
			obj.notify();
		}
	}
}

class RunnableImpl3 implements Runnable {

	private Object obj;
	
	public RunnableImpl3(Object obj) {
		this.obj = obj;
	}
	
	public void run() {
		System.out.println("run on RunnableImpl3");
		synchronized (obj) {
			System.out.println("obj to wait on RunnableImpl3");
			try {
				obj.wait(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("obj continue to run on RunnableImpl3");
		}
	}
}

打印结果

run on RunnableImpl2
睡眠3秒...
run on RunnableImpl1
obj to wait on RunnableImpl1
run on RunnableImpl3
obj to wait on RunnableImpl3
obj continue to run on RunnableImpl3
notify obj on RunnableImpl2
obj continue to run on RunnableImpl1

 


【Java面试题与答案】整理推荐

 

  • 8
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值