java中Synchronized关键字加锁操作

java中每一个对象都有一个内部锁
  1. 类实例对象锁(普通方法)
    synchronized void transfer01(int[] accounts, int from, int to, int amount) {
        while (accounts[from] < amount) {
            try {
                this.wait();
            } catch (InterruptedException exception) {
                exception.printStackTrace();
            }
        }
        accounts[from] = accounts[from] - amount;
        accounts[to] = accounts[to] + amount;
        this.notifyAll();
    }
  1. 普通对象锁(代码块)
    final Object object = new Object();
    void transfer02(int[] accounts, int from, int to, int amount) {
        synchronized (object) {
            while (accounts[from] < amount) {
                try {
                    object.wait();
                } catch (InterruptedException exception) {
                    exception.printStackTrace();
                }
            }
            accounts[from] = accounts[from] - amount;
            accounts[to] = accounts[to] + amount;
            object.notifyAll();
        }
    }
  1. 类对象锁(静态方法)
    synchronized static void transfer03(int[] accounts, int from, int to, int amount) {
        while (accounts[from] < amount) {
            try {
                ThreadTest.class.wait();
            } catch (InterruptedException exception) {
                exception.printStackTrace();
            }
        }
        accounts[from] = accounts[from] - amount;
        accounts[to] = accounts[to] + amount;
        ThreadTest.class.notifyAll();
    }
  1. 只能在获得对象内部锁的对象上调用wait()、notifyAll()、notify()方法,未获得锁的情况下直接调用会抛出java.lang.IllegalMonitorStateException异常
内部锁和条件的局限
  1. 不能中断一个正在试图获得锁的线程
  2. 试图获得锁时不能设定超时
  3. 每个锁仅有单一的条件
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值