• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
旧街古巷〃雨未停
每天进步一点
博客园    首页    新随笔    联系   管理    订阅  订阅

线程同步问题

package zxd.work622;

public class TestAccount extends Thread {
    private Account a = new Account();

    public void run() {
        for (int i = 0; i < 10; i++) {
            this.makeWithDraw(100);
            if (a.getBlance() < 0) {
                System.out.println("余额透支");
            }
        }
    }
    private synchronized void makeWithDraw(int money) {//线程同步
        synchronized (a) {  //线程同步
            if (money <= a.getBlance()) {
                System.out.println("准备取款");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                a.withDraw(money);
                System.out.println(Thread.currentThread().getName() + "取了"
                        + money + "余额:" + a.getBlance());
            } else {
                System.out.println("余额不足:" + Thread.currentThread().getName()
                        + "取款失败");
            }
        }
    }
    public static void main(String[] args) {
        TestAccount t = new TestAccount();
        Thread one = new Thread(t);
        Thread two = new Thread(t);
        one.setName("张三");
        two.setName("李四");
        one.start();
        two.start();


    }
}

 

posted @ 2017-06-22 18:37  旧街古巷〃雨未停  阅读(83)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3