/** * Sleep、WaitDemo * * @author suntao * @history 2020-02-11 14:30 suntao 新建 * @since JDK1.8 */ public class SleepWaitDemo { /** * sleep和wait的区别 * 1、sleep是Thread的方法,wait是Object类中的防范 * 2、sleep在任何地方都可以调用,wait只有在sychronized方法或sychronized块中进行使用; * 3、Thread.sleep只会让出cpu,不会导致对象锁的行为的改变; * Object.wait不仅可以让出cpu,也会释放锁 * @param args */ public static void main(String[] args) { Object lock = new Object(); new Thread(new Runnable() { @Override public void run() { System.out.println("Thread A wait get lock."); synchronized (lock){ System.out.println("Thread A get lock."); try { Thread.sleep(20); // 休眠20ms,模拟业务逻辑处理 System.out.println("Thread A do wait method.释放对象锁"); lock.wait(1000); // 对象锁等待,释放对象锁 System.out.println("Thread A is done."); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); try { // 确保Thread A 先执行,占用对象锁,以验证lock.wait可以释放对象锁 Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } new Thread(new Runnable() { @Override public void run() { System.out.println("Thread B wait get lock."); synchronized (lock){ System.out.println("Thread B get lock."); try { Thread.sleep(10); // 休眠10ms,模拟业务逻辑处理 System.out.println("Thread B is done."); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); } }
来源:https://www.cnblogs.com/xiaotao726/p/12295085.html