多线程通信
Posted hkmblogs
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程通信相关的知识,希望对你有一定的参考价值。
一、创建两个程序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()唤醒
以上是关于多线程通信的主要内容,如果未能解决你的问题,请参考以下文章