Java多线程经典例题

消费者与生产者的问题
 ·生产者负责生产数据,消费者负责取走数据
 ·生产者每生产完一组数据之后,消费者就要取走一组数据
  解决数据错位问题(非同步操作所造成):

class Info{ //信息初始化类
    private String title;
    private String content;
    private boolean flag = true;    //初始生产标记为True,代表可以生产
    //使用同步设置方法  (生产过程)
    public synchronized void set(String title, String content){
        //重复进入到set()里面,不能够生产,需要等待,其他线程不可进入抢占资源
        if(this.flag == false){     //代表以及有数据正在生产
            try {
                super.wait();   //其他线程需要等待
				//wait()需要等待notify()唤醒
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
        this.title = title;
        //等待1s种的生产时间
        try{
            Thread.sleep(100);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        this.content = content;
        this.flag = false;  //修改生产标记,代表正在生产,其他线程不可进入
        super.notify();     //唤醒其他等待线程
    }
    public synchronized void get(){
        if(this.flag == true){  //可以生产
            try{
                super.wait();
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
        /*一秒钟的生产时间*/
        try{
            Thread.sleep(1000);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        System.out.println(this.title+":"+this.content);
        this.flag = true;   //生产完成,可以生产
        super.notify();     //唤醒其他等待的线程
    }
}

class Producer implements Runnable{
    private Info info;  //引用Info类的线程对象
    public Producer(Info info){
        this.info = info;
    }
    /*与下面get()方法同步set(生产)数据*/
    @Override
    public void run() {
        for (int x=1; x<=100; x++){
            if(x % 2!=0){
                this.info.set(x+"-> "+"Item1 "," 12345");
            }else{
                this.info.set(x+"-> "+"Item2 "," abcde");
            }
        }
    }
}

class Customer implements Runnable{
    /*引用Info类里的线程对象*/
    private Info info;
    public Customer(Info info){
        this.info = info;
    }
    @Override
    public void run() {
        for (int x = 0; x<100; x++) {
            /*使用同步get()方法获取数据*/
            this.info.get();
        }
   }
}

public class ThreadDemo {
    public static void main(String[] args){
        Info info = new Info();
        //使用Runnable接口实现多线程
        new Thread(new Producer(info)).start();
        new Thread(new Customer(info)).start();
    }
}


 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值