java中sleep()同wait()有什么不同呢?
下文笔者将讲述sleep()同wait()方法的不同点,如下所示:
sleep是线程类(Thread)中的方法 sleep()方法的功能:设置线程暂停指定时间,此时其它线程会运行,等暂停时间到了之,会自动运行 sleep()方法不会释放对象锁 ---------------------------------------------------- wait()方法是Object类中的方法 wait()方法的功能:本线程放弃对象锁定,进入等待队列 当我们对此对象运行notify方法(或 notifyAll)后本线程才进入对象锁定池准备获得对象锁进入运行状态 ---------------------------------------------------------------------------------------------- sleep()方法退出运行的线程,让出CPU,不释放锁,指定时自动恢复运行 wait()方法暂时退出同步锁,进入等待队列,只有别的线程发出notify方法(或 notifyAll)后 ,wait()方法所处的线程才会得到运行例:
package com.java265.other;
publicclass TestClass {
public static void main(String[] args) {
new Thread(newThread1()).start();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(newThread2()).start();
}
private static class Thread1implements Runnable
{
@Override
public void run() {
synchronized (TestClass.class){
System.out.println("enterthread1...");
System.out.println("thread1is waiting");
try {
//释放锁有两种方式,第一种方式是程序自然离开监视器的范围
//也就是离开了 synchronized 关键字管辖的代码范围
//另一种方式就是在 synchronized 关键字管辖的代码内部调用监视器对象的 wait 方法
//这里,使用 wait 方法释放锁。
TestClass.class.wait();
} catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread1is going on...");
System.out.println("thread1is being over!");
}
}
}
private static class Thread2implements Runnable
{
@Override
public void run() {
synchronized (TestClass.class){
System.out.println("enterthread2...");
System.out.println("thread2notify other thread can release wait status..");
//由于 notify 方法并不释放锁
//即使 thread2调用下面的 sleep 方法休息了10毫秒,但 thread1仍然不会执行,因为 thread2没有释放锁,所以 Thread1无法得不到锁。
TestClass.class.notify();
System.out.println("thread2is sleeping ten millisecond...");
try {
Thread.sleep(10);
} catch (InterruptedExceptione) {
e.printStackTrace();
}
System.out.println("thread2is going on...");
System.out.println("thread2is being over!");
}
}
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


