多线程——生产消费模型

主界面

public class Master {
    public static  void main(String[] args) {
        //各个线程要用到的共享队列
        ArrayList<String> queue = new ArrayList<>();
        }

模拟生产者线程

public class ThreadProduce extends Thread {
    //指向共享队列
    public ArrayList<String> queue;

    public ThreadProduce(ArrayList<String> queue) {
        this.queue = queue;
    }

    public void run() {
        int id = 0;
        while(true){
            if(this.queue.size() == 0) {
                id++;
                String msg = "模拟数据"+id;
                //如果队列中没有数据就生成一个放进去
                this.queue.add(msg);
                System.out.println("生产者生产了数据"+msg);
            }

            try{
                Thread.sleep(10);
            }catch(Exception e){}

        }
    }
}

模拟消费者线程

public class ThreadCustomer extends Thread {
    //指向共享队列
    public ArrayList<String> queue;

    public ThreadCustomer(ArrayList<String> queue) {
        this.queue = queue;
    }

    public void run() {

        while(true){
            if(this.queue.size() > 0) {
                String msg = this.queue.remove(0);
                System.out.println("消费线程取出数据"+msg);
            }
            try{
                Thread.sleep(1000);
            }catch(Exception e){}

        }

    }
}

在主界面中启动线程

public class Master {
    public static  void main(String[] args) {
        //各个线程要用到的共享队列
        ArrayList<String> queue = new ArrayList<>();


            ThreadProduce tp = new ThreadProduce(queue);
            tp.start();
            System.out.println("生产线程已启动");


            ThreadCustomer tc = new ThreadCustomer(queue);
            tc.start();
            System.out.println("消费线程已启动");

    }
}

运行效果

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值