对于sleep()方法,我们首先要知道该方法是属于Thread类中的。而wait()方法,则是属于Object类中的。
sleep()方法导致了程序暂停执行指定的时间,让出cpu该其他线程,但是他的监控状态依然保持者,当指定的时间到了又会自动恢复运行状态。
在调用sleep()方法的过程中,线程不会释放对象锁。
而当调用wait()方法的时候,线程会放弃对象锁,进入等待此对象的等待锁定池,只有针对此对象调用notify()方法后本线程才进入对象锁定池准备
获取对象锁进入运行状态。
什么意思呢?
举个列子说明:
1 /**
2 *
3 */
4 package com.b510.test;
5
6 /**
7 * java中的sleep()和wait()的区别
8 * @author Hongten
9 * @date 2013-12-10
10 */
11 public class TestD {
12
13 public static void main(String[] args) {
14 new Thread(new Thread1()).start();
15 try {
16 Thread.sleep(5000);
17 } catch (Exception e) {
18 e.printStackTrace();
19 }
20 new Thread(new Thread2()).start();
21 }
22
23 private static class Thread1 implements Runnable{
24 @Override
25 public void run(){
26 synchronized (TestD.class) {
27 System.out.println("enter thread1...");
28 System.out.println("thread1 is waiting...");
29 try {
30 //调用wait()方法,线程会放弃对象锁,进入等待此对象的等待锁定池
31 TestD.class.wait();
32 } catch (Exception e) {
33 e.printStackTrace();
34 }
35 System.out.println("thread1 is going on ....");
36 System.out.println("thread1 is over!!!");
37 }
38 }
39 }
40
41 private static class Thread2 implements Runnable{
42 @Override
43 public void run(){
44 synchronized (TestD.class) {
45 System.out.println("enter thread2....");
46 System.out.println("thread2 is sleep....");
47 //只有针对此对象调用notify()方法后本线程才进入对象锁定池准备获取对象锁进入运行状态。
48 TestD.class.notify();
49 //==================
50 //区别
51 //如果我们把代码:TestD.class.notify();给注释掉,即TestD.class调用了wait()方法,但是没有调用notify()
52 //方法,则线程永远处于挂起状态。
53 try {
54 //sleep()方法导致了程序暂停执行指定的时间,让出cpu该其他线程,
55 //但是他的监控状态依然保持者,当指定的时间到了又会自动恢复运行状态。
56 //在调用sleep()方法的过程中,线程不会释放对象锁。
57 Thread.sleep(5000);
58 } catch (Exception e) {
59 e.printStackTrace();
60 }
61 System.out.println("thread2 is going on....");
62 System.out.println("thread2 is over!!!");
63 }
64 }
65 }
66 }
运行效果:
enter thread1... thread1 is waiting... enter thread2.... thread2 is sleep.... thread2 is going on.... thread2 is over!!! thread1 is going on .... thread1 is over!!!
如果注释掉代码:
1 TestD.class.notify();
运行效果:
enter thread1... thread1 is waiting... enter thread2.... thread2 is sleep.... thread2 is going on.... thread2 is over!!!
且程序一直处于挂起状态。
① 这两个方法来自不同的类分别是,sleep来自Thread类,和wait来自Object类。
sleep是Thread的静态类方法,谁调用的谁去睡觉,即使在a线程里调用b的sleep方法,实际上还是a去睡觉,要让b线程睡觉要在b的代码中调用sleep。
② 锁: 最主要是sleep方法没有释放锁,而wait方法释放了锁,使得其他线程可以使用同步控制块或者方法。
sleep不出让系统资源;wait是进入线程等待池等待,出让系统资源,其他线程可以占用CPU。一般wait不会加时间限制,因为如果wait线程的运行资源不够,再出来也没用,要等待其他线程调用notify/notifyAll唤醒等待池中的所有线程,才会进入就绪队列等待OS分配系统资源。sleep(milliseconds)可以用时间指定使它自动唤醒过来,如果时间不到只能调用interrupt()强行打断。
Thread.sleep(0)的作用是“触发操作系统立刻重新进行一次CPU竞争”。
③ 使用范围:wait,notify和notifyAll只能在同步控制方法或者同步控制块里面使用,而sleep可以在任何地方使用。
synchronized(x){
x.notify()
//或者wait()
}
原文:http://www.cnblogs.com/jiangzhaowei/p/7196659.html