Java基础面试操作题:线程同步代码块 两个客户往一个银行存钱,每人存三十次一次存一百。 模拟银行存钱功能,时时银行现金数。

package com.swift;

public class Bank_Customer_Test {
    public static void main(String[] args) {
        /*
         * 两个客户往一个银行存钱,每人存三十次一次存一百。 模拟银行存钱功能,时时银行现金数。
         */

        Customer customer = new Customer();
        new Thread(customer, "zhangsan").start();
        new Thread(customer, "lisi").start();
    }
}

class Bank {
    private static int sum = 0;

    public void setSum(int money) {
        sum = sum + money;
        System.out.println(Thread.currentThread().getName()+"存钱 :"+money+" 银行共有资金: "+sum);
    }

}

class Customer implements Runnable {
    private Bank bank = new Bank();

    public void run() {
        for (int i = 0; i < 30; i++) {
            synchronized("lock") {
                bank.setSum(100);
            }
        }
    }
}

 

posted @ 2018-01-20 20:58  Advancing-Swift  阅读(866)  评论(0编辑  收藏  举报