首页 > 编程语言 > 详细

java 中 sleep(1000) 和 wait(1000) 的区别?

时间:2017-01-08 16:20:30      阅读:181      评论:0      收藏:0      [点我收藏+]

1.首先 sleep 方法是Thread类中的静态方法,他的作用是使当前线程暂时睡眠指定的时间,可以不用放在synchronized方法或者代码块中,但是 wait 方法是Object类的方法,它是使当前线程暂时放弃监视对象的使用权进行等待,必须要放在synchronized方法或者代码块中

2.调用线程的sleep 方法当前线程会让出CPU给其他线程执行,但不会释放锁,依然占用锁的使用权,但是 wait方法会释放锁。

3.sleep方法到睡眠指定时间后会自动回复到可运行状态,但是wait方法需要另外一个拥有锁的对象调用 notify 方法进行唤醒,否则将一直挂起。

 

验证代码如下:

 1 package test.main.com;
 2 
 3 public class SleepAndWait {
 4     
 5     
 6     private static class Thread1 implements Runnable{
 7         @Override
 8         public void run() {
 9             synchronized (SleepAndWait.class) {
10                 System.out.println("thread 1 enter run method...");
11                 System.out.println("thread 1 start waiting...");
12                 try {
13                     SleepAndWait.class.wait();
14                 } catch (Exception e) {
15                     e.printStackTrace();
16                 }
17                 System.out.println("thread 1 ending waiting...");
18                 System.out.println("thread 1 is over...");
19             }
20         }
21     }
22     
23     
24     private static class Thread2 implements Runnable{
25 
26         @Override
27         public void run() {
28             synchronized (SleepAndWait.class) {
29                 System.out.println("thread 2 enter run method...");
30                 System.out.println("thread 2 sleeping...");
31                 SleepAndWait.class.notifyAll();
32                 
33                 try {
34                     Thread.sleep(10000);
35                 } catch (InterruptedException e) {
36                     e.printStackTrace();
37                 }
38                  
39                 System.out.println("thread2 is going on....");
40                 System.out.println("thread2 is over!!!");
41             }
42         }
43         
44     }
45     
46     public static void main(String[] args) {
47         new Thread(new Thread1()).start();
48         new Thread(new Thread1()).start();
49         new Thread(new Thread1()).start();
50         
51         try {
52             System.out.println("main Thread begin sleeping....");
53             Thread.sleep(8000);
54             System.out.println("main Thread end sleeping....");
55         } catch (InterruptedException e) {
56             e.printStackTrace();
57         }
58         
59         new Thread(new Thread2()).start();
60     }
61     
62 
63 }

 

java 中 sleep(1000) 和 wait(1000) 的区别?

原文:http://www.cnblogs.com/tuliang/p/6262043.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!