sleep和wait的区别
1.sleep是属于Thread的方法,而wait方法是属于Object类的
2.sleep方法对象不会释放对象锁,只是会暂停执行的指定时间,但是监控状态会保持着,当指定时间到了又会运行
当调用wait方法的时候,线程会释放对象锁,进入等待此对象的等待锁定池,需要执行notify()方法才进入对象锁定池准备,获取对象锁进入运行状态。
例子:
package com.test;
public class TestD {
public static void main(String[] args) {
new Thread(new Thread1()).start();
try {
Thread.sleep(1000);
}catch(Exception e){
e.printStackTrace();
}
new Thread(new Thread2()).start();
}
}
package com.test;
public class Thread1 implements Runnable{
@Override
public void run() {
synchronized (TestD.class){
System.out.println("进入 Thread1");
System.out.println("thread1在等待");
try {
TestD.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread1 is going");
System.out.println("Thread1 is over");
}
}
}
package com.test;
public class Thread2 implements Runnable{
@Override
public void run() {
synchronized (TestD.class){
System.out.println("进入thread2");
System.out.println("thread2在sleeping");
TestD.class.notify();
try {
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("thread2 is going");
System.out.println("thread2 is over");
}
}
}
不注释notify方法的运行结果:
进入 Thread1
thread1在等待
进入thread2
thread2在sleeping
thread2 is going
thread2 is over
Thread1 is going
Thread1 is over
注释notify方法的运行结果
进入 Thread1
thread1在等待
进入thread2
thread2在sleeping
thread2 is going
thread2 is over
解释:在sleep方法之后,注释了notify方法,线程进入挂起状态。