java线程之——sleep()与wait()的区别

sleep()Thread的方法,wait()Object的方法

如果线程进入了同步锁,sleep不会释放对象锁,wait会释放对象锁

sleep的作用就是让正在执行的线程主动让出CPU,给其它线程获得CPU的机会,在sleep指定的时间之后,CPU才会回到这个线程上继续往下执行,当线程进入了同步锁时,当别的线程也需要被加锁的资源时,sleep方法即使让出了CPU,别的线程也无法执行,因为无法获得锁。

wait方法是指在一个已经进入了同步锁的线程内,让自己暂时让出同步锁给别的线程用,只有等其他线程调用了notify或notifyAll方法后,才能去获得同步锁继续执行,需要注意的是,notify并不会释放锁,只是告诉调用过wait方法的线程可以去争取锁了,而不是马上得到锁。

此外在使用wait,notify,notifyAll方法的时候,要注意只能使用对象锁的持有者,即被封锁的对象来调用,不然会出IllegalMonitorStateException异常。

package javaBase;
/**
 * sleep()和wait()的区别
 * sleep()是Thread的方法,wait()是Object的方法
 * sleep不会释放封锁的资源,wait会释放封锁的资源
 * @author cnxno1
 *
 */
public class JB_047_SleepAndWait {
	public static void main(String[] args) {
		Thread thread1 = new Thread(new Thread1());
		Thread thread2 = new Thread(new Thread2());
		thread1.start();
		
		try {
			System.out.println("延迟5秒启动线程2");
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		thread2.start();
	}
}
/**
 * 公共资源类
 * @author cnxno1
 *
 */
class Resource{
	public static String resource = "public resource";
}
/**
 * 调用wait方法的线程
 * @author cnxno1
 *
 */
class Thread1 implements Runnable{
	@Override
	public void run(){
		synchronized(Resource.resource){
				System.out.println("this is thread1 , i hava the "+Resource.resource);
				System.out.println("this is thread1 , i'm waiting the "+Resource.resource);
				try{
					Resource.resource.wait();
				}catch(InterruptedException e){
					e.printStackTrace();
				}
				System.out.println("this is thread1,  i will going on...");
				System.out.println("this is the end of thread1.");
		}
	}
}

/**
 * 调用sleep方法的线程
 * @author cnxno1
 *
 */
class Thread2 implements Runnable{
	@Override
	public void run(){
		synchronized(Resource.resource){
			System.out.println("this is thread2 , i'm notifyAll thread...");
			Resource.resource.notifyAll();
			System.out.println("this is thread2 , i will sleep 10 seconds...");
			try {
				Thread.sleep(10000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("this is thread2,  i will going on...");
			System.out.println("this is the end of thread2.");
		}
	}
}

  运行的结果如下:

延迟5秒启动线程2
this is thread1 , i hava the public resource
this is thread1 , i'm waiting the public resource
this is thread2 , i'm notifyAll thread...
this is thread2 , i will sleep 10 seconds...
this is thread2, i will going on...
this is the end of thread2.
this is thread1, i will going on...
this is the end of thread1.

  可以看到thread1在调用了wait方法之后,thread2获得了同步锁,但是在thread2调用了sleep方法后,thread1并没有获得同步锁执行下去,而是在thread2 sleep了10秒执行完之后才获得了Resource.resource的锁得以执行完成。

 

posted @ 2014-03-11 00:07  苍枫露雨  阅读(774)  评论(0编辑  收藏  举报