gpt4 book ai didi

java - 为什么此代码会导致 illegalMonitorState 异常?

转载 作者:行者123 更新时间:2023-11-30 05:50:57 25 4
gpt4 key购买 nike

下面的代码试图将一个随机值插入循环队列并将其删除。但是,存在一些同步问题。我知道我可以使用更高级别的例程,我打算为生产代码这样做,但我很好奇为什么这不起作用?我在这里错过了什么?

public class CircularQueue {
int count;
int rear;
int front;
Object lock = new Object();
int size;
int[] array;
CircularQueue(int size)
{
this.size= size;
array = new int[size];
}

void enqueue(int number) throws InterruptedException
{
if(isFull())
lock.wait();

synchronized(lock)
{

array[rear] = number;
System.out.println("Rear is:"+ rear+ "value is:"+number+"Size is:"+size);

rear = (rear+1)%size;
count++;
}
lock.notify();

}

void dequeue() throws InterruptedException
{
if(isEmpty())
lock.wait();

synchronized(lock)
{
int retVal = 0;
retVal = array[front];
System.out.println("Front is:"+ front+ "value is:"+retVal);

front = (front+1)%size;
count--;
}

lock.notify();

}

boolean isFull()
{
if(count == size)
{
return true;
}
else
return false;

}

boolean isEmpty()
{
return count == 0;
}
}

//测试类

import java.util.Random;
public class App {

public static void main(String[] args) throws InterruptedException
{
final Random random = new Random();
final CircularQueue circularQueue = new CircularQueue(10);
Thread t1 = new Thread(new Runnable(){

@Override
public void run() {
try {
circularQueue.enqueue(random.nextInt(100));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

});
Thread t2 = new Thread(new Runnable(){

@Override
public void run() {
try {
circularQueue.dequeue();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

});

t1.start();
t2.start();
t1.join();
t2.join();

}

}

最佳答案

因为java.lang.Object#waitjava.lang.Object#notifyjava.lang.Object#notifyAll必须是从同步块(synchronized block)中调用。

作为一个解决方案(需要检查)你应该把你的条件放在同步块(synchronized block)中:

void enqueue(int number) throws InterruptedException
{

synchronized(lock)
{
if(isFull())
lock.wait();

array[rear] = number;
System.out.println("Rear is:"+ rear+ "value is:"+number+"Size is:"+size);

rear = (rear+1)%size;
count++;
lock.notify();
}
}

void dequeue() throws InterruptedException
{
synchronized(lock)
{
if(isEmpty())
lock.wait();

int retVal = 0;
retVal = array[front];
System.out.println("Front is:"+ front+ "value is:"+retVal);

front = (front+1)%size;
count--;
lock.notify();
}

}

关于java - 为什么此代码会导致 illegalMonitorState 异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13335367/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com