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
posted @ 2020-01-13 10:42  我是段先森  阅读(112)  评论(0编辑  收藏  举报