java sleep与wait的区别

最近被问到这个问题,查找资料后写个例子,可看出其中差别。
1、首先wait是Object的方法,sleep是Thread的方法。
2、object.wait被某线程调用,要确保该线程能监控该对象,否则抛出IllegalMonitorStateException。之后该线程放弃对次object的synchronized要求。此时其他需要

synchronized该object的线程可获得运行权。
thread.sleep使线程停滞,不释放其占用的锁。

 

下面的例子可以看清楚差别。

public class T {

	/**
	 * @param args
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws InterruptedException {
		// TODO Auto-generated method stub
		WaitRunner w1 = new WaitRunner(5000);
		w1.start();
		Thread.sleep(1000);
		WaitRunner w2 = new WaitRunner();
		w2.start();
		Thread.sleep(1000);
		WaitRunner w3 = new WaitRunner(2000);
		w3.start();
		Thread.sleep(1000);
		WaitRunner w4 = new WaitRunner(4000);
		w4.start();
		Thread.sleep(1000);
		WaitRunner w5 = new WaitRunner();
		w5.start();

		SleepRunner s1 = new SleepRunner(5000);
		s1.start();
		SleepRunner s2 = new SleepRunner();
		s2.start();
		SleepRunner s3 = new SleepRunner();
		s3.start();
		SleepRunner s4 = new SleepRunner();
		s4.start();
		SleepRunner s5 = new SleepRunner();
		s5.start();
	}

}

class WaitRunner extends Thread {
	private static Object lock = new Object();
	private int ms;
	public WaitRunner() {
		super();
		// TODO Auto-generated constructor stub
	}
	public WaitRunner(int ms) {
		super();
		this.ms = ms;
	}
	public void run() {
		synchronized(lock) {
			System.out.println(getName() + " is running....");
			if(ms > 0)
				try {
					lock.wait(ms);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
//			else
//				lock.notify();
			System.out.println(getName() + " is end....");
		}
	}
}

class SleepRunner extends Thread {
	private static Object lock = new Object();
	private int ms;
	public SleepRunner() {
		super();
		// TODO Auto-generated constructor stub
	}
	public SleepRunner(int ms) {
		super();
		this.ms = ms;
	}
	public void run() {
		synchronized(lock) {
			System.out.println(getName() + " is running....");
			if(ms > 0)
				try {
					sleep(ms);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			System.out.println(getName() + " is end....");
		}
	}
}


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值