java中的sleep()与wait()区别

 一、对于sleep()方法,咱们首先要知道该方法是属于Thread类中的。而wait()方法,则是属于Object类中的。ide

 二、sleep()方法致使了程序暂停执行指定的时间,让出cpu給其余线程,可是他的监控状态依然保持着,当指定的时间到了又会自动恢复运行状态。在调用sleep()方法的过程当中,线程不会释放对象锁。而当调用wait()方法的时候,线程会放弃对象锁,进入等待此对象的等待锁定池,只有针对此对象调用notify()方法后本线程才进入对象锁定池准备spa

获取对象锁进入运行状态。线程

eg:orm

public class TestThread {对象

public static void main(String [] args)it

{io

new Thread(new Thread1()).start();class

try {thread

Thread.sleep(5000);监控

} catch (InterruptedException e) {

e.printStackTrace();

}

new Thread(new Thread2()).start();

}

private static class Thread1 implements Runnable{

@Override

public void run() {

synchronized(TestThread.class)

{

System.out.println("线程一启动。。。。。");

System.out.println("线程一wait.....");

try {

TestThread.class.wait();

} catch (Exception e) {

// TODO: handle exception

}

System.out.println("线程一在此运行。。。。。");

System.out.println("线程一结束.....");

}

}

}

private static class Thread2 implements Runnable{


@Override

public void run() {


 synchronized (TestThread.class) {

                  System.out.println("thread2启动....");

                  System.out.println("thread2 is sleep....");

                  //只有针对此对象调用notify()方法后本线程才进入对象锁定池准备获取对象锁进入运行状态。

                  TestThread.class.notify();

                  //==================

                  //区别

                  //若是咱们把代码:TestD.class.notify();给注释掉,即TestD.class调用了wait()方法,可是没有调用notify()

                 //方法,则线程永远处于挂起状态。

                 try {

                      //sleep()方法致使了程序暂停执行指定的时间,让出cpu给其余线程,

                      //可是他的监控状态依然保持者,当指定的时间到了又会自动恢复运行状态。

                      //在调用sleep()方法的过程当中,线程不会释放对象锁。

                      Thread.sleep(5000);

                  } catch (Exception e) {

                      e.printStackTrace();

                 }

                 System.out.println("thread2 is going on....");

                System.out.println("thread2 is over!!!");

             }

}

}


}



结果:

线程一启动。。。。。

线程一wait.....

thread2启动....

thread2 is sleep....

thread2 is going on....

thread2 is over!!!

线程一在此运行。。。。。

线程一结束.....


若是注释掉代码:

TestThread.class.notify();

结果:

线程一启动。。。。。

线程一wait.....

thread2启动....

thread2 is sleep....

thread2 is going on....

thread2 is over!!!

相关文章
相关标签/搜索