java多线程:生产者和消费者模式(wait-notify) : 单生产和单消费

单生产者

package com.example.t.pc;

import java.util.List;

//生产者
public class P {
    private List list;

    public P(){
    }

    public P(List list){
        this.list = list;
    }

    public void add(){
        while(true){
            synchronized (list){
                try {
                    System.out.println("3s----------------");
                    Thread.sleep(3000);
                    if(list != null && list.size() > 0){
                        System.out.println("生产者:停止生产");
                        list.wait(); //锁释放 原地等待
                        System.out.println("P ok解锁");
                    }

                    list.add("123");
                    list.notify();
                    System.out.println("生产者:开始生产");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

单消费者

package com.example.t.pc;

import java.util.List;

//消费者
public class C {
    private List list;

    public C(){
    }

    public C(List list){
        this.list = list;
    }

    public void sub(){
        while (true){
            synchronized (list){
                try {
                    System.out.println("1s----------------");
                    Thread.sleep(1000);
                    if(list != null && list.size() > 0){
                        list.remove(0);
                        list.notify();
                        System.out.println("消费者: 开始消费");
                    }else{
                        System.out.println("消费者: 停止消费");
                        list.wait();//锁释放 原地等待
                        System.out.println("C ok解锁");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

执行

package com.example.t.pc;

import java.util.ArrayList;
import java.util.List;

public class Main {

    public static void main(String[] args) {
         List list = new ArrayList();

         new Thread(() -> {
            P p = new P(list);
            p.add();
        }).start();

        new Thread(()->{
            C c = new C(list);
            c.sub();
        }).start();
    }




}

 

posted @ 2019-10-15 11:16  Peter.Jones  阅读(292)  评论(0编辑  收藏  举报