The Java language has built-in synchronized keywords for multi-threaded synchronization, which greatly facilitates the compilation of multi-threaded programs in Java. However, the use of the synchronized keyword alone cannot meet all the requirements for multi-thread synchronization. As you know, synchronized can only synchronize methods or code blocks. If an application needs to synchronize across multiple methods, synchroinzed cannot be used. There are many synchronization mechanisms in C ++, such as semaphores, mutex, and temporary zone. In Java, we can also build such a synchronization tool at a higher level based on synchronized features to facilitate our use.
Currently, a Java synchronization toolkit compiled by Doug Lea is widely used. You can learn more about this package here:
Http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html
This toolkit is under the control of JCP as JSR166 and will be a formal component of JDK1.5. This article does not describe this toolkit in detail, but introduces a variety of synchronization mechanisms, and provides examples of implementation of such synchronization mechanisms, which is not an industrial implementation. However, we will refer to some code snippets of industrial implementation in this synchronization package of Doug Lea.
In this example, we still use the Account class in the previous article. However, we will write a new ATM class to simulate the ATM. Using an ATM tester class, we will generate 10 ATM threads, john's account is also queried, withdrawn, and deposited. The Account class has been modified to meet the needs of this article:
- ImportJava. util.HashMap;
- ImportJava. util.Map;
- ClassAccount {
- StringName;
- // Float amount;
- // Use a Map to simulate persistent Storage
- Static MapStorage =New HashMap();
- Static{
- Storage. put ("John ",New Float(1000.0f ));
- Storage. put ("Mike ",New Float(8000000f ));
- }
- PublicAccount (StringName ){
- // System. out. println ("new account:" + name );
- This. Name = name;
- // This. amount = (Float) storage. get (name). floatValue ();
- }
- Public Synchronized VoidDeposit (FloatAmt ){
- FloatAmount = ((Float) Storage. get (name). floatValue ();
- Storage. put (name,New Float(Amount + amt ));
- }
- Public Synchronized VoidWithdraw (FloatAmt)ThrowsInsufficientBalanceException {
- FloatAmount = ((Float) Storage. get (name). floatValue ();
- If(Amount> = amt)
- Amount-= amt;
- Else
- Throw NewInsufficientBalanceException ();
- Storage. put (name,New Float(Amount ));
- }
- Public FloatGetBalance (){
- FloatAmount = ((Float) Storage. get (name). floatValue ();
- ReturnAmount;
- }
- }
In the new Account class, we use a HashMap to store Account information. The Account is used by the ATM class after logging on through login:
- Public ClassATM {
- Account acc;
- // As a demo, password verification is omitted
- Public BooleanLogin (StringName ){
- If(Acc! =Null)
- Throw New Html "target =" _ blank ">IllegalArgument