zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    【NOIP模拟赛】正方形大阵
    【优化王牌】二分查找
    【Ah20160703】咏叹 By C_SUNSHINE
    【NOIP模拟赛】lover——心上人
    【小奇模拟赛】小奇挖矿2
    【NOIP模拟赛】工资
    关于博客装修的说明
    【快速处理】分块算法
    【集训】 考试笔记
    【HDNOIP】HD201404最短路径
  • 原文地址:https://www.cnblogs.com/duanxiansen/p/12186184.html
Copyright © 2011-2022 走看看