Java多线程编程遇到IllegalMonitorStateException
meet IllegalMonitorStateException when doing multi-thread programming in Java
我写了一个简单的程序来学习同步块。程序如下:
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() 函数,并且我已经将锁设置为同步的参数。为什么我还有异常?
您的 release_lock
方法有问题。您在调用 lock.notifyAll().
之前将 lock
重新分配给 0
,这意味着将在未锁定的新 Integer 对象上调用 notifyAll。将代码更改为以下以解决问题。
public static void release_lock() {
synchronized(lock) {
lock.notifyAll();
lock = 0;
}
}
我写了一个简单的程序来学习同步块。程序如下:
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() 函数,并且我已经将锁设置为同步的参数。为什么我还有异常?
您的 release_lock
方法有问题。您在调用 lock.notifyAll().
之前将 lock
重新分配给 0
,这意味着将在未锁定的新 Integer 对象上调用 notifyAll。将代码更改为以下以解决问题。
public static void release_lock() {
synchronized(lock) {
lock.notifyAll();
lock = 0;
}
}