Java多线程——生产者与消费者问题

Java多线程之生产者消费者问题:
生产者生产了消费者才能消费,消费者消费了才能生产。

/**
 * FileName: MultithreadingDemo
 * Author:   十七
 * Date:     2020/3/30 12:31
 * Description: 多线程实战——生产者消费者问题
 * History:
 * notes:
 */
package com.test;
class Message{
    private String title;
    private String content;
    //表示生产与消费的形式,flag=true,允许生产,不允许消费;flag=false,不允许生产,允许消费
    private boolean flag;
    //利用synchronized解决同步问题,保证了数据的一致
    public synchronized void set(String title,String content){
        if(this.flag==true){ //无法生产,等待被消费
            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=true;    //已经生产过了
        super.notify();     //唤醒等待的线程
    }
    public synchronized String get(){
        if(this.flag==false){ //还未生产,需要等待
            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=false; //继续生产
            super.notify(); //唤醒等待线程
        }
    }
}
class Producer implements Runnable{
    private Message msg;
    public Producer(Message msg){
        this.msg=msg;
    }
    @Override
    public void run() {
        for(int x=0;x<10;x++){
            if(x%2==0){
                this.msg.set("0","0");
            }else {
                this.msg.set("1","1");
            }
        }
    }
}
class Consumer implements Runnable{
    private Message msg;
    public Consumer(Message msg){
        this.msg=msg;
    }
    @Override
    public void run() {
        for(int x=0;x<10;x++){
            System.out.println(this.msg.get());
        }
    }
}
public class MultithreadingDemo {
    public static void main(String[] args) throws Exception{
        Message msg=new Message();
        new Thread(new Producer(msg)).start();//启动生产者线程
        new Thread(new Consumer(msg)).start();//启动消费者线程
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值