多线程通信
一、创建两个程序MyThread1.java和MyThread2.java
public class MyThread1 extends Thread { private Object lock; public MyThread1(Object lock) { super(); this.lock = lock; } @Override public void run() { try { synchronized (lock) { System.out.println("开始 wait time=" + System.currentTimeMillis()); lock.wait(); System.out.println("结束 wait time=" + System.currentTimeMillis()); } } catch (InterruptedException e) { e.printStackTrace(); } } }
public class MyThread2 extends Thread { private Object lock; public MyThread2(Object lock) { super(); this.lock = lock; } @Override public void run() { synchronized (lock) { System.out.println("开始notify time=" + System.currentTimeMillis()); lock.notify(); System.out.println("结束notify time=" + System.currentTimeMillis()); } } }
二、创建测试类:
public class Test { public static void main(String[] args) { try { Object lock = new Object(); MyThread1 t1 = new MyThread1(lock); t1.start(); Thread.sleep(3000); MyThread2 t2 = new MyThread2(lock); t2.start(); } catch (InterruptedException e) { e.printStackTrace(); } } }
三、结果显示:
由上我们可以得知,在调用wait()方法的过程中,会释放锁等待线程被notify()唤醒,在调用notify()时,不会释放所资源,等待线程执行完成
没有停止的脚步,只有倒下去的脚步