java多线程问题

java多线程问题

synchronized, wait, notify结合 典型场景生产者消费者问题

package demo;


public class Test5 {
    private static final int MAX_PRODUCT = 5;
    private static final int MIN_PRODUCT = 0;
    private static int product = 0;

    public synchronized void produce()
    {
        if(Test5.product >= MAX_PRODUCT)
        {
            try
            {
                System.out.println("产品已满,请稍候再生产");
                wait();  

            }
            catch(InterruptedException e)
            {
                e.printStackTrace();
            }
            return;
        }
        Test5.product++;
        System.out.println("生产者生产第" + Test5.product + "个产品.");
        notifyAll();   //通知等待区的消费者可以取出产品了
    }

    /**
     * 消费者从店员取产品
     */
    public synchronized void consume()
    {
        if(Test5.product <= MIN_PRODUCT)
        {
            try 
            {
                System.out.println("缺货,稍候再取");
                wait(); 
            } 
            catch (InterruptedException e) 
            {
                e.printStackTrace();
            }
            return;
        }

        System.out.println("消费者取走了第" + Test5.product + "个产品.");
        Test5.product--;
        notifyAll();   //通知等待去的生产者可以生产产品了

    }


    public static void main(String[] args) {
        Test5 t = new Test5();
        while(true) {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    t.produce();

                }
            }).start();
            new Thread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    t.consume();
                }
            }).start();
        }

    }
}

运行效果:

 

posted @ 2020-09-29 16:18  LW_20171224  阅读(52)  评论(0编辑  收藏  举报