正文

用java模拟生产者与消费者问题2006-04-25 22:05:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/super/13167.html

分享到:

package lly;

public class Box
{
    private int value;

    private boolean available = false;

    public synchronized int get()
    {
        while (available == false)
        {
            try
            {
                // 等待生产者写入数据
                wait();
            } catch (InterruptedException e)
            {
                // TODO: handle exception
                e.printStackTrace();
            }
        }
        available = false;
        // 通知生产者数据已经被取走,可以再次写入数据
        notifyAll();
        return value;
    }

    public synchronized void put(int value)
    {
        while (available == true)
        {
            try
            {
                // 等待消费者取走数据
                wait();
            } catch (InterruptedException e)
            {
                // TODO: handle exception
                e.printStackTrace();
            }
        }
        this.value = value;
        available = true;
        // 通知消费者可以来取数据
        notifyAll();
    }

}
package lly;

public class Consumer extends Thread
{
    private Box box;

    private String name;

    public Consumer(Box b, String n)
    {
        box = b;
        name = n;
    }

    public void run()
    {
        int value = 0;
        for (int i = 1; i < 6; i++)
        {

            value = box.get();
            System.out.println("Consumer " + name + " consumed: " + value);

            try
            {
                sleep((int) (Math.random() * 10000));
            } catch (InterruptedException e)
            {
                // TODO: handle exception
                e.printStackTrace();
            }
        }
    }

}
package lly;

public class Producer extends Thread
{
    private Box box;

    private String name;

    public Producer(Box b, String n)
    {
        box = b;
        name = n;
    }

    public void run()
    {
        for (int i = 1; i < 6; i++)
        {
            box.put(i);
            System.out.println("Producer " + name + " produced: " + i);

            try
            {
                sleep((int) (Math.random() * 10000));
            } catch (InterruptedException e)
            {
                // TODO: handle exception
                e.printStackTrace();
            }
        }
    }

}
package lly;

public class ProducerConsumer
{

    /**
     * @param args
     */
    public static void main(String[] args)
    {
        // TODO 自动生成方法存根
        Box box = new Box();
        Producer p = new Producer(box, "p");
        Consumer c = new Consumer(box, "c");

        p.start();
        c.start();

    }

}

阅读(4212) | 评论(0)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

暂无评论
您需要登录后才能评论,请 登录 或者 注册