java多线程——生产者和消费者

使用同步方法来保证数据的一致性,使用wait() 和 notify() 、notifyAll()方法来解决重复操作。


public class Test {
    public static void main(String[] args) {
        Message msg = new Message();
        Producer producer = new Producer(msg);
        Consumer consumer = new Consumer(msg);
        new Thread(producer,"producer").start();
        new Thread(consumer, "consumer").start();
    }
}
class Producer implements Runnable {
    private Message msg;

    public Producer(Message msg) {
        this.msg = msg;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {

            if (i % 2 == 0) {
                this.msg.set("小明-", "第一帅哥");
            } else {
                this.msg.set("小qiang-", "第一猥琐男");
            }
        }
    }
}

class Consumer implements Runnable {
    private Message msg;

    public Consumer(Message msg) {
        this.msg = msg;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {

            System.out.println(this.msg.get());
        }

    }
}

class Message {
    private String title;
    private String content;
    private boolean flag;
    // flag = true; 允许生产,禁止消费
    // flag = false; 允许消费,禁止生产
    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public synchronized void set(String titile, String content) {

        if (!this.flag) {
            try {
                super.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.title = titile;
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.content = content;
        this.flag = false;
        super.notify();
    }
    public synchronized String get() {
        if (this.flag) {
            try {
                super.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        try {
            return this.title + this.content;
        } finally {
            this.flag = false;
            super.notify();
        }

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值