• synchronized 关键字


    synchronized 关键字解决的是多个线程之间访问资源的同步性,保证被它修饰的方法或者代码块在任意时间段内只能被一个线程进行访问。

    public class Acount {
        private int money;
        public Acount(int money) {
            this.money = money;
        }
        
        public synchronized void getMoney(int money){
            while (this.money < money || this.money == 0) {
                System.out.println("取款:"+money+",当前余额为:"+this.money+",余额不足,请等待:");
                try {
                    wait();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            this.money = this.money - money;
            System.out.println("取出:"+money+" 还剩余:"+this.money);
        }
        
        public synchronized void setMoney(int money) {
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                // TODO: handle exception
            }
            this.money = this.money + money;
            notifyAll();
            System.out.println("存入:"+money+" 还剩余:"+this.money);
        }
        
        /**
         * @param args
         */
        public static void main(String[] args) {
            Acount acount = new Acount(0);
            Blank blank = new Blank(acount);
            Customer customer = new Customer(acount);
            
            Thread thread1 = new Thread(blank);
            Thread thread2 = new Thread(customer);
            
            thread1.start();
            thread2.start();
        }
    
    }
    
    class Blank extends Thread{
        Acount acount;
        public Blank(Acount acount){
            this.acount = acount;
        }
        
        public void run(){
            while(true){
                int money = (int)(Math.random() * 1000);
                acount.setMoney(money);
            }
        }
    }
    
    class Customer extends Thread{
        Acount acount;
        public Customer(Acount acount){
            this.acount = acount;
        }
        
        public void run(){
            while(true) {
                int money = (int)(Math.random() * 1000);
                acount.getMoney(money);
            }
        }
    }
    View Code
  • 相关阅读:
    Centos搭建PHP5.3.8+Nginx1.0.9+Mysql5.5.17
    初识Mongodb总结
    初识Mongodb之[CURD]PHP版
    Centos搭建Samba
    PHP图像处理(二) GraphicsMagick 安装扩展及使用方法
    Vcastr3.0开源在线flv播放器
    自动更新@version svn版本号信息
    Centos安装Memcache
    MVC演化
    JAVA与.NET的相互调用——TCP/IP相互调用基本架构
  • 原文地址:https://www.cnblogs.com/duanxiansen/p/12186184.html
Copyright © 2020-2023  润新知