Read the previous article:
Java multi-thread synchronization tutorial-BusyFlag or Lock (on)
We first develop a BusyFlag class, similar to Simaphore in C ++.
- Public ClassBusyFlag {
- Protected ThreadBusyflag =Null;
- Protected IntBusycount = 0;
- Public Synchronized VoidGetBusyFlag (){
- While(TryGetBusyFlag () =False){
- Try{
- Wait ();
- }Catch(ExceptionE ){}
- }
- }
- Private Synchronized BooleanTryGetBusyFlag (){
- If(Busyflag =Null){
- Busyflag =Thread. CurrentThread ();
- Busycount = 1;
- Return True;
- }
- If(Busyflag =Thread. CurrentThread ()){
- Busycount ++;
- Return True;
- }
- Return False;
- }
- Public Synchronized VoidFreeBusyFlag (){
- If(GetOwner () =Thread. CurrentThread ()){
- Busycount --;
- If(Busycount = 0 ){
- Busyflag =Null;
- Notify ();
- }
- }
- }
- Public Synchronized ThreadGetOwner (){
- ReturnBusyflag;
- }
- }
NOTE: Refer to Scott Oaks & Henry Wong Java Thread
BusyFlag has three public methods: getBusyFlag, freeBusyFlag, and getOwner, which are used to obtain the busy sign, release the busy sign, and obtain the thread that currently occupies the busy sign. It is also very simple to use this BusyFlag. You only need to call the getBusyFlag () of BusyFlag where the lock is needed. When the locked resources are used up, call the freeBusyFlag () of BusyFlag () you can. Next we will begin to transform the Account and ATM classes in the previous article, and apply the BusyFlag tool class so that only one thread can access the same Account at the same time. First, we need to transform the Account class. A BusyFlag object is built in the Account, and the Account is locked and unlocked through this flag object:
- ImportJava. util.Collections;
- ImportJava. util.HashMap;
- ImportJava. util.Map;
- ClassAccount {
- StringName;
- // Float amount;
- BusyFlag flag =NewBusyFlag ();
- // Use a Map to simulate persistent Storage
- Static MapStorage =New HashMap();
- Static{
- Storage. put ("John ",New Float(1000.0