生产者和消费者多线程模拟

package yn.ngems.cn;
class Message{
    private String title;
    private String content;
    private boolean flag = true;//true,生产,不消费;false,消费,不生产
    public synchronized void set(String title,String content) {
        if(this.flag == false) {
            try {
                super.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.title = title;
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.content = content;
        this.flag = false;
        super.notify();
    }
    public synchronized String get() {
        if(this.flag == true) {
            try {
                super.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            return this.title + "  --  " + this.content;
        }finally {
            this.flag = true;
            super.notify();
        }
    }
}
class Productor implements Runnable{
    private Message msg;
    public Productor(Message msg) {
        this.msg = msg;
    }
    @Override
    public void run() {
        for(int x = 0;x < 50;x ++) {
            if(x % 2 == 0) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                this.msg.set("AAA", "aaa");
            }else {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                this.msg.set("BBBB", "bbbbbbbb");
            }
        }
    }
}
class Consumer implements Runnable{
    private Message msg;
    public Consumer(Message msg) {
        this.msg = msg;
    }
    @Override
    public void run() {
        for(int x = 0;x < 50;x ++) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(this.msg.get());
        }
    }
}
public class ThreadDemo {
    public static void main(String[] args) {
        Message msg = new Message();
        new Thread(new Productor(msg)).start();
        new Thread(new Consumer(msg)).start();
    }
}
思路:Message类是生产者和消费者的链接,从初次的简单Java类来做,会出现很多问题,一步步分析,数据是否同步,锁机制,生产和消费不能同时进行,需要有等待,设置开关进行等待判断和唤醒,增加休眠时间,为了更好的展现问题所在。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值