package test; /** * author:songyan * date: 2019/11/10 **/ public class demo2 { public static void main(String[] args) { SaveWindow save = new SaveWindow(); Thread user1 = new Thread(save); Thread user2 = new Thread(save); user1.start(); user2.start(); } } /** * 银行类 */ class Bank{ int money = 0; Object obj = new Object(); public void saveMoney(int addMoney){ synchronized (obj){ money = money + addMoney; System.out.println("money "+money); } } } /** * 银行的存钱窗口 */ class SaveWindow implements Runnable{ Bank bank = new Bank(); @Override public void run() { for (int i=0;i<3;i++){ bank.saveMoney(100); } } }
通过同步代码块解决安全问题