多线程sleep与wait的区别

package com.huawei.interview;

public class Thread1 implements Runnable{

	public void run() {
       synchronized (MultiThread.class){
    	   		System.out.println("enter thread1!");
    	   		System.out.println("thread1 is waiting");
    	   		try{
    	   			MultiThread.class.wait();
    	   		}catch (Exception e) {
					e.printStackTrace();
				}
    	   		System.out.println("thread1 is going on");
    	   		System.out.println("thread1 is being  over");
       };
	}

}



package com.huawei.interview;

public class Thread2 implements Runnable{

	public void run() {
		synchronized (MultiThread.class){
			System.out.println("enter thread2");
			System.out.println("thread2 notify other thread can release wait status");
			MultiThread.class.notify();
			System.out.println("thread2 is sleeping for ten ms");
			try{
				Thread.sleep(10);
			}catch (Exception e) {
				e.printStackTrace();
			}
	   		System.out.println("thread2 is going on");
	   		System.out.println("thread2 is being  over");
		};
	}

}



package com.huawei.interview;

public class MultiThread {
	public static void main(String[] args) {

		new Thread(new Thread1()).start();
		try{
			Thread.sleep(10);
		}catch (Exception e) {
			e.printStackTrace();
		}
		new Thread(new Thread2()).start();
	}
}



运行结果:
enter thread1!
thread1 is waiting
enter thread2
thread2 notify other thread can release wait status
thread2 is sleeping for ten ms
thread2 is going on
thread2 is being  over
thread1 is going on
thread1 is being  over



解释:
sleep就是正在运行的线程主动让出cpu,cpu去执行其他线程,在sleep指定的时间过后,cpu

才会回到这个线程上继续运行,如果当前线程进入了同步锁,sleep方法并不会释放锁,即使

当前线程使用了sleep让出了cpu,但其他被同步锁挡住了的线程也无法得到执行。wait是指一

个已经进入了同步锁的线程内,让自己暂时让出同步锁,以便其他正在等待此锁的线程可以得

到同步锁并运行,只有其他线程调用了notify方法(notify方法并不会释放锁,只是告诉调用

过wait的线程可以参与获得锁的竞争了,但是不会马上得到锁,因为锁还在其他线程手中,别

人还没释放)调用wait方法的线程就会解除wait状态,程序可以再次获得锁后继续向下运行

你可能感兴趣的:(java,多线程)