【发布时间】:2016-10-13 04:22:33
【问题描述】:
我写了一个简单的程序来学习同步块。程序如下:
public class SychronizedBlock {
static int balance = 0;
static Integer lock = 0;
public static void deposit(int amt) {
Thread t1 = new Thread(new Runnable() {
public void run() {
acquire_lock();
int holdings = balance;
balance = holdings + amt;
System.out.println("deposit " + amt + ", balance: " + balance);
release_lock();
}
});
t1.start();
}
public static void acquire_lock() {
synchronized(lock) {
while (lock == 1) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lock = 1;
}
}
public static void release_lock() {
synchronized(lock) {
lock = 0;
lock.notifyAll();
}
}
public static void test1() {
balance = 0;
deposit(500);
deposit(500);
}
public static void main(String[] args) {
test1();
}
}
但是,在运行程序时,我遇到了 IllegalMonitorStateException。我想我已经将 wait() 和 notifyAll() 函数放在了同步块中,并且我已经将锁设置为同步的参数。为什么我仍然有异常?
【问题讨论】:
标签: java multithreading wait synchronized notify