多线程 money

来源:互联网 发布:软件测试有哪些行业 编辑:程序博客网 时间:2024/05/16 10:21
package com.phj20110824.Thread;public class Account {private int balance;//余额public  synchronized void withdraw(int money){balance=balance+money;}public  synchronized void getMoney(int money){//if(money<=this.balance){balance=balance-money;//}}public int getBalance(){return this.balance;}}
package com.phj20110824.Thread;public class GetMoney implements Runnable {private Account account;public GetMoney(Account account) {this.account = account;}@Overridepublic void run() {// TODO Auto-generated method stubfor (int i = 0; i < 10; i++) {this.account.getMoney(500);}}}package com.phj20110824.Thread;public class AddMoney implements Runnable {private Account account;public AddMoney(Account account) {this.account = account;}@Overridepublic void run() {// TODO Auto-generated method stubfor (int i = 0; i < 10; i++) {this.account.withdraw(500);}}}
package com.phj20110824.Thread;public class AccountTest {public static void main(String[] args) {Account account = new Account();GetMoney getmoney = new GetMoney(account);AddMoney addmoney = new AddMoney(account);new Thread(getmoney).start();new Thread(addmoney).start();try {Thread.sleep(2000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println(account.getBalance());}}


	
				
		
原创粉丝点击