您的位置:首页 > 编程语言 > Java开发

一个简单的java生产着消费者模式的代码

2013-03-28 17:13 435 查看
package test;

public class SycnStack{

    private static Integer value =0;

    private static Object LOCK = new Object();

    public static void main(String[] args)

    {

        SycnStack ss = new SycnStack();

        ss.new AThread().start();

        ss.new BThread().start();

    }

   

    public static void produce()

    {

        synchronized (LOCK)

        {

            while(value == 3)

            {

                System.out.println("值超过3,停止增加");

                try

                {

                    LOCK.wait();

                } catch (InterruptedException e) {

                    e.printStackTrace();

                }

            }

            value ++;

            System.out.println("生产第 " + value + "个");

            LOCK.notify();

        }

    }

   

    public static void custom()

    {

        synchronized (LOCK)

        {

            while(value == 0){

                System.out.println("值小于或等于0,停止减少");

                try {

                    LOCK.wait();

                } catch (InterruptedException e) {

                    e.printStackTrace();

                }

            }

            System.out.println("消费第 " + value + "个");

            value --;

            LOCK.notify();

        }

    }

   

    class AThread extends Thread

    {

        public void run()

        {

            while(true)

            {

                produce();

                try

                {

                    Thread.sleep((long)(Math.random() * 3000));

                }

                catch (InterruptedException e)

                {

                }

            }

        }

    }

   

    class BThread extends Thread

    {

        public void run()

        {

            while(true)

            {

                custom();

                try

                {

                    Thread.sleep((long)(Math.random() * 3000));

                }

                catch (InterruptedException e)

                {

                }

            }

        }

    }

}

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: