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
  • 相关阅读:
    最近很烦心情糟糕透了
    面试心得
    CSS之按钮过滤
    JavaScript之动态背景登陆表单
    VsCode自定义快捷键,一次运行两个或多个Command命令
    Go优化浅谈
    go语言圣经第六章笔记
    go 语言圣经第六章习题
    go 内存对齐
    go语言圣经第五章部分习题
  • 原文地址:https://www.cnblogs.com/duanxiansen/p/12186184.html
Copyright © 2011-2022 走看看