jingtao416
2013-06-24 21:20
浏览 434
已采纳

一个java生产者消费者代码的问题

一个生产者消费者的代码,使用lock和condition实现。

[code="java"]
import java.util.concurrent.locks.Condition;

import java.util.concurrent.locks.Lock;

import java.util.concurrent.locks.ReentrantLock;

//生产/消费者模式

public class Basket {

Lock lock = new ReentrantLock();

// 产生Condition对象

Condition produced = lock.newCondition();

Condition consumed = lock.newCondition();

boolean available = false;

public void produce() throws InterruptedException {

lock.lock();

try {

if (available) {

produced.await(); // 放弃lock进入睡眠

}

System.out.println("Apple produced.");

available = true;

consumed.signal(); // 发信号唤醒等待这个Condition的线程

} finally {

lock.unlock();

}

}

public void consume() throws InterruptedException {

lock.lock();

try {

if (!available) {

consumed.await(); // 放弃lock进入睡眠

}

/* 吃苹果 */

System.out.println("Apple consumed.");

available = false;

produced.signal(); // 发信号唤醒等待这个Condition的线程

} finally {

lock.unlock();

}

}

}
[/code]

[code="java"]
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

//测试用类
public class ConditionTester {

public static void main(String[] args) throws InterruptedException {
    final Basket basket = new Basket();

    // 定义一个producer
    Runnable producer = new Runnable() {
        public void run() {
            try {
                basket.produce();
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    };

    // 定义一个consumer
    Runnable consumer = new Runnable() {
        public void run() {
            try {
                basket.consume();
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    };

    // 各产生10个consumer和producer
    ExecutorService service = Executors.newCachedThreadPool();

    for (int i = 0; i < 4; i++)
        service.submit(consumer);

    Thread.sleep(2000*2);

    for (int i = 0; i < 4; i++)
        service.submit(producer);

    service.shutdown();
}

}
[/code]

以上代码我觉的执行结果应该是一个Apple prodeced 跟着一个App consumed, 就是说如果生产一个苹果,那么它应该立即被消费掉,但是实际的执行结果却不一定,有时候的执行结果为:
[code="java"]
Apple produced.
Apple consumed.
Apple produced.
Apple produced.
Apple consumed.
Apple consumed.
Apple produced.
Apple consumed.
[/code]

出现了连续生产两次苹果,我想问问大牛们是这是什么原因啊?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

6条回答 默认 最新

  • jinnianshilongnian 2013-06-25 07:36
    最佳回答

    跟406657836 说的类似,但还是不完全一样;
    答案及解决方案在:
    [url]http://jinnianshilongnian.iteye.com/blog/1893690[/url]

    评论
    解决 无用
    打赏 举报
查看更多回答(5条)

相关推荐 更多相似问题