开发者

Getting an exception when performing Condition awaits?

开发者 https://www.devze.com 2023-02-16 12:59 出处:网络
I am getting an Exception everytime I run the following multithreaded code with Monitors. http://pastebin.com/jTGR98W9

I am getting an Exception everytime I run the following multithreaded code with Monitors.

http://pastebin.com/jTGR98W9 http://pastebin.c开发者_开发技巧om/hKvuDX2d

Everytime I perform a condition signal, I get an exception, which says that it should be exclusive, it is however exclusive, given that it is synchronized. Or am I doing something wrong?

Thanks


You are mixing the old intrinsic locks and their signaling mechanism (synchronized, wait and notify) with the new Lock and Condition classes, though they don't have any relationship. This is a source for confusion, so I'd stick to one of them (preferably Lock and Condition).

Your problem is probably caused by not holding the lock that is associated to the condition when you are calling signal(). Surround the methods with calls to lock() and unlock():

public void canEat(String name) {
   lock.lock();
   try {
       eaters.add(name);
       if (eaters.size() > 0) {
          canFeed.signal();
       }
   } finally {
       lock.unlock();
   }
}

The same needs to be done for the other synchronized methods.

0

精彩评论

暂无评论...
验证码 换一张
取 消