sleep和wait的区别

public class SleepAndWait {

public static void main(String[] args) {
new Thread(new Thread1()).start();
try {
//sleep不会释放锁对象,但是导致了程序暂停执行指定的时间,让出cpu给其他线程,
//但是他的监控状态依然保持者,当指定的时间到了又会自动恢复运行状态。
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
}
new Thread(new Thread2()).start();
}

private static class Thread1 implements Runnable{
//@Override
public void run(){
synchronized (SleepAndWait.class) {
System.out.println("I am thread1===");
System.out.println("thread1 is sleep===");
System.out.println("thread1 暂停5秒---------------------");
try {
//调用wait()方法,线程会放弃对象锁,进入等待此对象的等待锁定池
SleepAndWait.class.wait();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("thread1 is notify====");
System.out.println("thread1 is over====");
System.out.println("thread1 释放了锁 被notify---------------------");
}
}
}

private static class Thread2 implements Runnable{
//@Override
public void run(){
synchronized (SleepAndWait.class) {

System.out.println("I am thread2===");
System.out.println("thread2 is over===");
System.out.println("thread2 ---------------------");
try {
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
}
//只有对当前对象调用notify()方法后本线程才进入对象锁定池准备获取对象锁进入运行状态
//如果没有该方法,则线程永远处于挂起状态
SleepAndWait.class.notify();

System.out.println("thread2 is run====");
System.out.println("thread2 is over===");
}
}
}
}

/**

*运行结果

*I am thread1===
*thread1 is sleep===
*thread1 暂停5秒---------------------
*I am thread2===
*thread2 is over===
*thread2 ---------------------
*thread2 is run====
*thread2 is over===
*thread1 is notify====
*thread1 is over====
*thread1 释放了锁 被notify---------------------


* sleep 是线程Thread中的静态方法,必须指定暂停的时间, 必须异常处理 ,sleep给其他方法运行时不考虑优先级,执行sleep之后转入阻塞状态

 * yield() 方法只会给相同优先级或者更高的优先级运行,执行之后转入就绪状态
* wati 是object中的方法  必须放在synchronized block中,否则会在运行时报“java.lang.IllegalMonitorStateException”异常
*/

原文地址:https://www.cnblogs.com/xp0813/p/11025264.html