码迷,mamicode.com
首页 > 编程语言 > 详细

多线程通信

时间:2020-06-25 13:28:50      阅读:51      评论:0      收藏:0      [点我收藏+]

标签:image   cat   方法   http   override   图片   显示   sleep   err   

一、创建两个程序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()唤醒

 

   

多线程通信

标签:image   cat   方法   http   override   图片   显示   sleep   err   

原文地址:https://www.cnblogs.com/hkMblogs/p/13191522.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!