The most significant application is of course bank deposits and withdrawals, not the number of access and the actual occurrence of a different situation.
Synchronized keyword.
classBankAccount {Private intBalance = 100; Public intGetBalance () {returnbalance; } Public voidWithdraw (intamount) {Balance= Balance-amount; }} Public classRyanandmonicajobImplementsRunnable {PrivateBankAccount account =NewBankAccount (); Public Static voidMain (string[] args) {//TODO auto-generated Method StubRyanandmonicajob Thejob =NewRyanandmonicajob (); Thread One=NewThread (thejob); Thread=NewThread (thejob); One.setname ("Ryan."); Two.setname ("Monica"); One.start (); Two.start (); } Public voidrun () { for(intx = 0; x < 10; X + +) {Makewithdrawal (10); if(Account.getbalance () < 0) {System.out.println ("Overdrawn!"); } } } Private synchronized voidMakewithdrawal (intamount) { if(Account.getbalance () >=amount) {System.out.println (Thread.CurrentThread (). GetName ()+ ' about-to withdraw '); Try{System.out.println (Thread.CurrentThread (). GetName ()+ "is going to sleep"); Thread.Sleep (500); } Catch(Interruptedexception ex) {ex.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName ()+ "woke up."); Account.withdraw (amount); System.out.println (Thread.CurrentThread (). GetName ()+ "completes the withdrawl"); } Else{System.out.println ("Sorry, not enough for" +Thread.CurrentThread (). GetName ()); } }}
Ryan is on to withdraw
Ryan is going to sleep
Ryan woke up.
Ryan completes the withdrawl
Ryan is on to withdraw
Ryan is going to sleep
Ryan woke up.
Ryan completes the withdrawl
Ryan is on to withdraw
Ryan is going to sleep
Ryan woke up.
Ryan completes the withdrawl
Ryan is on to withdraw
Ryan is going to sleep
Ryan woke up.
Ryan completes the withdrawl
Ryan is on to withdraw
Ryan is going to sleep
Ryan woke up.
Ryan completes the withdrawl
Ryan is on to withdraw
Ryan is going to sleep
Ryan woke up.
Ryan completes the withdrawl
Ryan is on to withdraw
Ryan is going to sleep
Ryan woke up.
Ryan completes the withdrawl
Ryan is on to withdraw
Ryan is going to sleep
Ryan woke up.
Ryan completes the withdrawl
Ryan is on to withdraw
Ryan is going to sleep
Ryan woke up.
Ryan completes the withdrawl
Ryan is on to withdraw
Ryan is going to sleep
Ryan woke up.
Ryan completes the withdrawl
Sorry, not enough for Monica
Sorry, not enough for Monica
Sorry, not enough for Monica
Sorry, not enough for Monica
Sorry, not enough for Monica
Sorry, not enough for Monica
Sorry, not enough for Monica
Sorry, not enough for Monica
Sorry, not enough for Monica
Sorry, not enough for Monica
Java Access Object Properties, if the open multi-threading, remember the relevant access method as an atomic operation definition