1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| public class Account { String name; double balance; public Account(String name) { this.name=name; this.balance=0; } public void put(double value) { if(value>0) this.balance+=value; } public double get(double value) { if(value<=0) return 0; if(value<=this.balance) this.balance-=value; else { value=this.balance; this.balance=0; } return value; } } public class SaveLock extends Thread { private Account account; private double value; public SaveLock(Account account,double value) { this.account=account; this.value=value; } public void run() { synchronized(this.account) { double howmatch=this.account.balance; try {Thread.sleep(1); } catch(InterruptedException ex) {} this.account.put(this.value); System.out.println(this.account.name+"账户:现有"+howmatch+",存入"+this.value+",余额"+this.account.balance); } } } class FetchLock extends Thread{ private Account account; private double value; public FetchLock(Account account,double value) { this.account=account; this.value=value; } public void run() { synchronized(this.account) { double howmatch = this.account.balance; try { Thread.sleep(1); } catch(InterruptedException ex) {} System.out.println( this.account.name+"账户:现有"+howmatch+",取走"+this.account.get(this.value)+",余额"+this.account.balance); } } } public class Main {
public static void main(String args[]) { Account wang = new Account("Wang"); (new SaveLock(wang,100)).start(); (new SaveLock(wang,200)).start(); (new FetchLock(wang,300)).start(); }
}
|