在Java中尝试使用ReNANTTROLK实现生产者消费者
Condition producerlock = lock.newCondition();
Condition consumerlock = lock.newCondition();
它有两个条件,一个是生产者,另一个是消费者。
这里我们有一个带有两个方法producer consumer和一个堆栈的processor类
Stack<Integer> hellostrack = new Stack<>();
public void produce() throws InterruptedException {
lock.tryLock();
System.out.println("inside producer method");
while (true) {
try {
if (hellostrack.size() > 8) {
System.out.println("stack is full its time for me to go to sleep");
producerlock.await();
}
System.out.println("thread is alive and kicking");
hellostrack.add(new Random().nextInt());
consumerlock.signalAll();
} finally {
System.out.println("Exception occours in producer Thread");
lock.unlock();
}
}
}
public void consume() throws InterruptedException{
System.out.println("inside consumer method");
lock.tryLock();
try {
while (true) {
if (hellostrack.isEmpty()) {
System.out.println("stack is empty im going to sleep");
consumerlock.await();
} else {
System.out.println("poping elelmts from stock" + hellostrack.pop());
consumerlock.signalAll();
}
} }finally {
System.out.println("Exception occours at consumer");
lock.unlock();
}
}
正如您所看到的,当堆栈达到某个极限时,生产者将进入休眠状态,当堆栈为空时,生产者也会进入休眠状态。
但当我用两条线运行它们时
Processor p = new Processor();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
p.consume();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread t12 = new Thread(new Runnable() {
@Override
public void run() {
try {
p.produce();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t1.start();
t12.start();
i get illegal state exception
inside consumer method
stack is empty im going to sleep
inside producer method
thread is alive and kicking
Exception occours in producer Thread
thread is alive and kicking
Exception occours in producer Thread
Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
at java.base/java.util.concurrent.locks.ReentrantLock$Sync.tryRelease(ReentrantLock.java:149)
at java.base/java.util.concurrent.locks.AbstractQueuedSynchronizer.release(AbstractQueuedSynchronizer.java:1302)
at java.base/java.util.concurrent.locks.ReentrantLock.unlock(ReentrantLock.java:439)
at Processor.produce(Processor.java:30)
at Processor$2.run(Processor.java:76)
at java.base/java.lang.Thread.run(Thread.java:834)
poping elelmts from stock891164354
poping elelmts from stock-1958956829
stack is empty im going to sleep