java sleep与wait的区别

时间:2023-01-12 15:33:59

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

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

java sleep与wait的区别

 

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

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....");
}
}
}