sleep与wait的区别,详细解答(通过代码验证)

 1 package com.ysq.test;
 2 
 3 /**
 4  * sleep与wait的区别:
 5  * @author ysq
 6  *
 7  */
 8 public class SleepAndWait {
 9 
10     public static void main(String[] args) {
11      //启动线程1
12         new Thread(new Thread1()).start();
13         try {
14             Thread.sleep(4*1000);//休眠10ms
15         } catch (InterruptedException e) {
16             // TODO Auto-generated catch block
17             e.printStackTrace();
18         }
19         //启动线程2
20         new Thread(new Thread2()).start();    
21 
22     }
23     private static class Thread1 implements Runnable{
24 
25         @Override
26         public void run() {
27 
28             synchronized (SleepAndWait.class){//这里没有使用this,因为为了使两个线程使用同一监听器,因为在Thread2里面的this和这个Thread1的this不是同一个对象。
29                 System.out.println("enter thread1...");
30                 System.out.println("thread1 is waiting");
31                 try {
32                     //使用wait方法释放同步锁。
33                     SleepAndWait.class.wait();
34                 } catch (InterruptedException e) {
35                     // TODO Auto-generated catch block
36                     e.printStackTrace();
37                 }
38                 System.out.println("thread1 is going on...");
39                 System.out.println("thread1 is being over!");
40             }
41         }
42     }
43     
44     private static class Thread2 implements Runnable{
45 
46         @Override
47         public void run() {
48             synchronized (SleepAndWait.class){
49                 System.out.println("enter thread2...");
50                 System.out.println("thread2 notify other thread can release wait status..");
51                 //只有线程2(其他线程)调用了notify方法    调用wait方法的线程(这里是线程1)就会解除wait状态和程序可以再次得到锁后继续向下运行
52                 SleepAndWait.class.notify();
53                 System.out.println("thread2 is sleeping ten millisecond...");
54                 try {
55                     //但由于notify不能释放同步锁
56                     Thread.sleep(4*1000);//因此线程2虽然已进入休眠状态,但线程1仍然不用运行,因为线程2使用的是notify()
57                 } catch (InterruptedException e) {
58                     // TODO Auto-generated catch block
59                     e.printStackTrace();
60                 }
61                 System.out.println("thread2 is going on...");
62                 System.out.println("thread2 is being over!");
63 
64             }
65         }
66         
67     }
68 }

 总结:通过上面的代码,我们可以登场sleep和wait的区别,如下:

   1,sleep是线程类Thread的方法,wait是Object类中的方法

   2,sleep此线程暂停执行指定时间,将执行机会给其他线程,但是监控状态依然保持,到时后会自动恢复。调用sleep不会释放对象锁

   3,对象调用wait方法导致本线程放弃对象锁,进入等待此对象的等待锁定池,只有针对此对象发出notify方法(或notifyAll)后本线程才进入对象锁定池准备获得对象锁进入运行状态
   4,最主要是sleep方法没有释放锁,而wait方法释放了锁,使得其他线程可以使用同步控制块或者方法。
   5,wait,notify和notifyAll只能在同步控制方法或者同步控制块里面使用,而sleep可以在
    任何地方使用
   synchronized(x){
      x.notify()
     //或者wait()
   }

生活赋予我们一种巨大的和无限高贵的礼品,这就是青春:充满着力量,充满着期待志愿,充满着求知和斗争的志向,充满着希望信心和青春。
原文地址:https://www.cnblogs.com/ysq0908/p/4813791.html