java中每一个对象都有一个内部锁
- 类实例对象锁(普通方法)
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();
}
- 普通对象锁(代码块)
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();
}
}
- 类对象锁(静态方法)
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();
}
- 只能在获得对象内部锁的对象上调用wait()、notifyAll()、notify()方法,未获得锁的情况下直接调用会抛出
java.lang.IllegalMonitorStateException
异常
内部锁和条件的局限
- 不能中断一个正在试图获得锁的线程
- 试图获得锁时不能设定超时
- 每个锁仅有单一的条件