多线程 wait 释放当前锁

证明 wait 只释放当前锁

/**
 * 描述:     证明wait只释放当前的那把锁
 */
public class WaitNotifyReleaseOwnMonitor {

    private static volatile Object resourceA = new Object();
    private static volatile Object resourceB = new Object();

    public static void main(String[] args) {
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (resourceA) {
                    System.out.println("Thread1 got resourceA lock.");
                    synchronized (resourceB) {
                        System.out.println("Thread1 got resourceB lock.");
                        try {
                            System.out.println("Thread1 releases resourceA lock.");
							//将 A 锁释放,那么其他线程将可以获得这把锁的使用权
                            resourceA.wait();

                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });

        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
				//获取 A 锁,由于 thread1 已经释放了 A 锁,所以可以成功取到
                synchronized (resourceA) {
                    System.out.println("Thread2 got resourceA lock.");
                    System.out.println("Thread2 tries to resourceB lock.");

					//这里无法获取 resourceB 锁,因为在 thread1 中并没有释放 B 锁,只释放了 A 锁
                    synchronized (resourceB) {
                        System.out.println("Thread2 got resourceB lock.");
                    }
                }
            }
        });

        thread1.start();
        thread2.start();
    }
}

运行结果

Thread1 got resourceA lock.
Thread1 got resourceB lock.
Thread1 releases resourceA lock.
Thread2 got resourceA lock.
Thread2 tries to resourceB lock.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值