JAVA的wait和notify

多线程经常会接触到线程交互场景,wait和notify、notifyAll就是起到这个作用,三个方法必须要在synchronized锁区域内执行,也就是必须要有当前对象的monitor(锁)。

wait: 阻塞当前线程,交出锁的控制权,等待下一次获取锁继续上次的执行
notify:通知等待当前对象的monitor的线程进行唤醒(注:只能唤醒一个,后续在当前锁区域内的代码还会继续执行)
notifyAll:与notify功能相同,唤醒全部等待当前对象monitor的线程,不过最终还是只有一个被系统选中

以一个示例演示轮流执行A、B、C线程的操作:

package com.healist.coder;

public class ThreadLearn {

    public static void main(String[] args) throws InterruptedException {
        Object obj1 = new Object();
        Object obj2 = new Object();
        Object obj3 = new Object();

        Thread1 th1 = new Thread1("A", obj3, obj1);
        Thread1 th2 = new Thread1("B", obj1, obj2);
        Thread1 th3 = new Thread1("C", obj2, obj3);

        th1.start();
        Thread.sleep(100);
        th2.start();
        Thread.sleep(100);
        th3.start();
    }

}


class Thread1 extends Thread {

    private String name;

    private Object obj1;
    private Object obj2;

    public Thread1() {}

    public Thread1(String name, Object obj1, Object obj2) {
        this.name = name;
        this.obj1 = obj1;
        this.obj2 = obj2;
    }

    @Override
    public void run(){
        System.out.println(name + " COME");
        int num = 5;
        while(num>0) {
            synchronized (obj1) {
                synchronized (obj2) {
                    obj2.notify();
                    num--;
                    System.out.println(name + " notify");
                }
                try {
                    System.out.println(name + " wait");
                    obj1.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        System.out.println(name + " GO");
    }

}

输出结果:

A COME
A notify
A wait
B COME
B notify
B wait
C COME
C notify
C wait
A notify
A wait
B notify
B wait
C notify
C wait
A notify
A wait
B notify
B wait
C notify
C wait
A notify
A wait
B notify
B wait
C notify
C wait
A notify
A wait
B notify
B wait
C notify
C wait
A GO
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值