67.Java-资源抢夺案例(使用synchronized)

  • 调用类
package com.test.thread;

public class Home {

    public static void main(String[] args) {
        
        ShareRegion share = new ShareRegion();
        
        new Thread(new Producer(share)).start();
        new Thread(new Consumer(share)).start();
        
    }
    
}
  • 资源共享类
package com.test.thread;

public class ShareRegion {
    
    private String name;
    private String sex;
    
    boolean isProduce = true;
    
    synchronized public void setterData(String name,String sex) {
        
        try {
            if (!isProduce) {
                this.wait();
            }

            this.name = name;
            Thread.sleep(10);
            this.sex = sex;
            
            isProduce = false;
            this.notifyAll();
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
    
    synchronized public void getterData() {

        try {
            if(isProduce) {
                this.wait();
            }
            System.out.println(this.name+"/"+this.sex);
            isProduce = true;
            this.notifyAll();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
}

  • 生产者
package com.test.thread;

import java.lang.Runnable;

public class Producer implements Runnable{
    
    private ShareRegion share = null;
    
    public Producer(ShareRegion share){
        this.share = share;
    }
    
    @Override
    public void run() {
        
        for (int i = 0; i < 50; i++) {
            if (i%2 == 0) {
                share.setterData("春哥", "男");
            }else {
                share.setterData("凤姐", "女");
            }
        }
        
    }

    

}

  • 消费者
package com.test.thread;

import java.lang.Runnable;

public class Consumer implements Runnable{
    
    private ShareRegion share = null;
    public Consumer(ShareRegion share){
        this.share = share;
    }
    
    @Override
    public void run() {
        // TODO Auto-generated method stub
        for (int i = 0; i < 50; i++) {
            share.getterData();
        }
    }

}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,169评论 19 139
  • 在这里, 用我的文字, 给低谷的你我力量, 为你我的心灵回家导航, 为迷失的你我重新寻回信仰, 为你我的人生添加风...
    美善的希瑞阅读 1,216评论 0 0
  • 文/孙小山 曾经我问你,如果世界末日了,你希望和谁在一起?你不假思索的看着我的眼睛特别真诚的说:妈妈和你! 可是世...
    孙小山阅读 6,707评论 13 3
  • 公司注销流程: 主要分为七步: 工商注销备案→注销登报公告→国税注销→地税注销→工商注销→代码注销→银行注销 注销...
    钱包你都瘦了阅读 3,982评论 0 0
  • 提前声明:作者不拥有靠谱的金融知识,因此下文可能出现诸多错误。本文的目的仅仅是整理自己近期的观察,如果还能吸引一些...
    jasonzhao阅读 2,695评论 0 1

友情链接更多精彩内容