本帖最后由 草貌路飞 于 2013-7-9 10:37 编辑
本来是要照着毕老师的代码写的,可以记错了,把应该在生产线程中的while(true)放到生产方法中去了。导致出现问题IllegalMonitorStateException,虽然知道问题所在了,但不明白这个问题是怎么产生的。哪位同学帮忙解释下问题产生的流程。- import java.util.concurrent.locks.Condition;
- import java.util.concurrent.locks.ReentrantLock;
- public class NewThreadDemo
- {
- public static void main(String[] args)
- {
- Product p = new Product();
- new Thread(new ProThread(p)).start();
- new Thread(new ConsThread(p)).start();
- }
- }
- class Product
- {
- private int proNum = 0;
- private boolean hasProduct = false;
-
- private ReentrantLock lock = new ReentrantLock();
- private Condition condition = lock.newCondition();
- public void produce()
- {
- lock.lock();
- while(true)//这里写错了,while(true)应该放在run里面的。
- {
- try
- {
- while(hasProduct)
- {
- System.out.println(Thread.currentThread().getName() + ":::::::wait");
- condition.await();
- }
- System.out.println(Thread.currentThread().getName() + ":produce:" + ++proNum);
- hasProduct = true;
- condition.signal();
- }
- catch(Exception e)
- {
- e.printStackTrace();
- }
- finally
- {
- lock.unlock();
- }
- }
- }
- public void consume()
- {
- lock.lock();
- try
- {
- while(!hasProduct)
- {
- System.out.println(Thread.currentThread().getName() + ":::::::wait");
- try{condition.await();}catch(Exception e){e.printStackTrace();}
- }
- System.out.println(Thread.currentThread().getName() + "::consume::" + proNum);
- hasProduct = false;
- condition.signal();
- }
- catch(Exception e)
- {
- e.printStackTrace();
- }
- finally
- {
- lock.unlock();
- }
- }
- }
- class ProThread implements Runnable
- {
- private Product product;
-
- ProThread(Product product)
- {
- this.product = product;
- }
-
- public void run()
- {
- product.produce();
- }
- }
- class ConsThread implements Runnable
- {
- private Product product;
-
- ConsThread(Product product)
- {
- this.product = product;
- }
- public void run()
- {
- while(true)
- product.consume();
- }
- }
复制代码 |
-
1.jpg
(23.13 KB, 下载次数: 0)
这是执行结果,每次结果都是一样的
|