我试图从另一个线程运行方法notify()
一个特定的线程。我面对java.lang.IllegalMonitorStateException
这两个线程都在主类中启动。
注意:
这三个都是不同的类。
主班
public class queueCheck {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
BlockingQueue<testObjectClass> queue = new LinkedBlockingQueue<testObjectClass>();
Producer producer = new Producer(queue);
Consumer consumer = new Consumer(queue);
Thread produceThread = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
producer.produce();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
});
Thread consumerThread = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
consumer.consume();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
});
producer.setConsumerThread(consumerThread);
consumer.setProducerThread(produceThread);
produceThread.start();
consumerThread.start();
}
}
生产商类别
class Producer {
BlockingQueue<testObjectClass> queue;
testObjectClass objectSample = new testObjectClass("TEST", "TEST");
Thread consumerThread;
public void setConsumerThread(Thread t1) {
this.consumerThread = t1;
}
public Producer(BlockingQueue<testObjectClass> outQueue) {
// TODO Auto-generated constructor stub
this.queue = outQueue;
}
public void produce() throws InterruptedException {
int i = 0;
while (true) {
synchronized (this) {
// Producer thread waits while list is full
try {
while (!queue.isEmpty()) {
// Notifies the consumer thread that now it can start consuming
this.wait();
}
i = i + 1;
objectSample.setValues("String ", String.valueOf(i));
queue.put(objectSample);
System.out.println("Adding element: " + objectSample.stringMessage());
consumerThread.notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
消费阶层
class Consumer {
BlockingQueue<testObjectClass> queue;
testObjectClass objectSample;
Thread producerThread;
public void setProducerThread(Thread t1) {
this.producerThread = t1;
}
public Consumer(BlockingQueue<testObjectClass> outQueue) {
// TODO Auto-generated constructor stub
this.queue = outQueue;
}
// Function called by consumer thread
public void consume() throws InterruptedException {
while (true) {
synchronized (this) {
//Consumer thread waits while list is empty.
while (queue.isEmpty()) {
this.wait();
}
testObjectClass objectX = queue.take();
System.out.println("\t Taking element: " + objectX.stringMessage());
producerThread.notify();
}
}
}
}
帮助类
class testObjectClass {
private String test1;
private String test2;
public testObjectClass(String testString1, String testString2) {
this.test1 = testString1;
this.test2 = testString2;
}
public void setValues(String testString1,String testString2) {
this.test1 = testString1;
this.test2 = testString2;
}
public String stringMessage() {
return test1 + test2;
}
}
最佳答案
https://examples.javacodegeeks.com/java-basics/exceptions/java-lang-illegalmonitorstateexception-how-to-solve-illegalmonitorstateexception/
使用此链接可获得一些详细信息。在这里,您将使用一个对象获取一个锁,并使用另一个对象释放相同的锁。使用共享库获取锁并释放该锁。