验证:
1、在我们的第一个线程先start之后呢,我们的主线程就sleep 10 ms,次让第二个线程start.
* 那么第一个线程开始执行之后,获得同步锁,然后wait一秒钟,在第一个线程wait一秒钟的时候,第二个线程已经开始
* 执行,如果此时,我们的线程一并没有释放lock的话,那么线程二就会被阻塞,不能执行代码里面的逻辑,如果释放锁的话,
* 第二个线程是可以执行的。
public class WaitSleepDemo { public static void main(String[] args) { final Object lock = new Object(); new Thread(new Runnable() { @Override public void run() { System.out.println("threada A waitting to a lock"); synchronized (lock) { System.out.println("thread A get a lock"); try { Thread.sleep(20); System.out.println("thread A wait method"); lock.wait(1000); System.out.println("thread A is done"); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); //为了使第一段先执行 try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } new Thread(new Runnable() { @Override public void run() { System.out.println("threada B waitting to a lock"); synchronized (lock) { System.out.println("thread B get a lock"); try { System.out.println("thread B sleep 10 ms"); Thread.sleep(20); System.out.println("thread B is done"); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); } }
执行结果:
2、掉个个之后呢?可以看出B是连续执行的,也就是说B sleep一秒钟的同时,并没有放出资源,等到休眠玩一秒钟,又继续执行,B完全执行完才会释放出资源。
public class WaitSleepDemo { public static void main(String[] args) { final Object lock = new Object(); new Thread(new Runnable() { @Override public void run() { System.out.println("threada B waitting to a lock"); synchronized (lock) { System.out.println("thread B get a lock"); try { System.out.println("thread B sleep 10 ms"); Thread.sleep(1000); System.out.println("thread B is done"); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); //为了使第一段先执行 try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } new Thread(new Runnable() { @Override public void run() { System.out.println("threada A waitting to a lock"); synchronized (lock) { System.out.println("thread A get a lock"); try { Thread.sleep(20); System.out.println("thread A wait method"); lock.wait(1000); System.out.println("thread A is done"); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); } }
结果: