读书人

线程同步-Synchronized-银行提款实例

发布时间: 2012-12-18 12:43:41 作者: rapoo

线程同步--Synchronized--银行取款实例

package com.cwc.util;/** * Copyright(c), 2011-2100 * @description:create an account and two payee,they sharing the same account,so variable is static * @file name: com.cwc.util.BankThread.java * @create: by author axis on Mar 3, 20113:08:45 PM * @since:  JDK1.6u21 */public class BankThread {private static Account account = new Account(1000);private static Customer depositOne = new Customer(account);private static Customer depositTwo = new Customer(account);public static void main(String[] args) {depositOne.drawMoney(800);depositTwo.drawMoney(800);Thread depositOneThread = new Thread(depositOne,"depositTwo");Thread depositTwoThread = new Thread(depositTwo,"depositTwo");depositOneThread.start();depositTwoThread.start();}}class Account{public int residualMoney;public Account(int initMoney){residualMoney = initMoney;}//execute this method,lock current object;you can also use synchronized(this){}  (synchronized block)public synchronized void drawMoney(int drawMoney){String name = Thread.currentThread().getName();if (drawMoney > residualMoney) {System.out.println(name + ": The balance of account is insufficient!");}else {System.out.println(name + " drawMoney: "+drawMoney+"¥");try {//enlarge errorThread.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}//update residualMoney of accountresidualMoney -= drawMoney;System.out.println("This account remains: "+residualMoney+"¥\r\n");}} }class Customer implements Runnable{private Account account;private int drawMoney;public Customer(Account account){this.account = account;}public void drawMoney(int drawMoney){this.drawMoney = drawMoney;}public void run(){account.drawMoney(drawMoney);}}

?线程同步-Synchronized-银行提款实例

?

?

?

?

?

?

?

?

读书人网 >编程

热点推荐