Zhang Xiaoxiang, Java high-paying video and PPT sharing

Source: Internet
Author: User

Recently, due to the company's business needs, the original use of C ++ is now changed to Java. There is no way. It took me some time to read java. I feel that Zhang Xiaoxiang's high-paying video tutorials are quite good!

However, I did not find that the document (Zhang Xiaoxiang's ppt) took some time. On the Internet, I used Zhang Xiaoxiang's PPT as a small part and compiled it into a word article. You can download the required documents!

Connection: http://www.verycd.com/topics/239368/

The blog garden cannot contain attachments.

Senior Software Talent practical training expert

INSTRUCTOR: Zhang Xiaoxiang

Chapter 1: Eclipse skills

  1. Workspace and Project
    Required: Switch the work room and import Project
  2. Perspective and view set the javac and Java of the entire workspace. Set the javac of a single project and Java. Can Java of higher version run the program compiled by javac of lower version? Can a lower version of java run a later version of javac compiled program? An example is provided in the application.
  3. The Shortcut Key Binding and code template use the shortcut key to improve work efficiency.
  4. Static Import
    The import statement can be used to import a class or all classes in a package.
    Import static statements to import a static method or all static methods in a class

 

Chapter 2: Java syntax

  1. Variable parameters
    Problem: the number of parameters accepted by a method is not fixed, for example, system. out. println (countscore (2, 3, 5); system. out. println (countscore (,); variable parameter features: can only appear at the end of the parameter list; remember this... it is located between the variable type and the variable name, and there are no spaces before and after it. When the variable parameter method is called, the compiler implicitly creates an array for the variable parameter, in the method body, you can access variable parameters in the form of arrays.
  2. For (type variable name: Set variable name) iteration variable must be defined in! Collection variables can be arrays or collection classes that implement the iterable interface.
    Public static int add (int x, Int... ARGs)
    {Int sum = x; For (INT Arg: ARGs) {sum + = ARG;} return sum ;}
  3. Automatic packing and automatic unpacking
    Integer num1 = 12;
    System. Out. println (num1 + 12 );
    Integer num1 = 12; integer num2 = 12; this is equal, <= 127 is true system. out. println (num1 = num2); integer num3 = 129; this part is not equal because it is an object integer num4 = 129; system. out. println (num3 = num4 );
    Integer num5 = integer. valueof (12 );
    Integer num6 = integer. valueof (12 );
    This is the same as system. Out. println (num5 = num6 );
  4. Enumeration:

Why is there an enumeration problem: how to define the day of the week or the gender variable? Assume that we use 1-7 to indicate Monday to Sunday, but some may write it as int weekday = 0; or even using constants cannot prevent exceptions. Enumeration is to make a variable of a type have only one of several fixed values. Otherwise, the compiler reports an error. Enumeration allows the compiler to control the invalid values filled in the source program during compilation. Normal variables cannot be implemented in the development phase. How to Implement the enumeration function using a common class and define a weekday class to simulate the enumeration function. Private constructor each element uses a public static member variable to indicate that there can be several public methods or abstract methods. When nextday is defined using an abstract method, a large number of if. Else statements are transferred into independent classes.
Examples of basic enumeration applications:
Defines the weekday enumeration. Extended: Values, valueof, name, tostring, ordinal, and other methods of enumeration classes (Remember, the lecture class should be introduced before the custom method, and the lecture should be smoother). Summary: enumeration is a special class. Each element of this class is an instance object of this class. For example, you can call weekday. sun. getclass (). getname and weekday. class. getname ().
Advanced enumeration applications
Enumeration is equivalent to a class. You can also define constructor, member variables, common methods, and abstract methods. The enumeration element must be located in the first part of the enumeration body. A semicolon must be placed after the enumeration element list to be separated from other members. Place member methods or variables in enumeration before enumeration elements, and the compiler reports errors. Enumeration constructor with constructor must be defined as private. If there are multiple constructor methods, which constructor should I choose? The enumeration elements Mon and Mon () have the same effect. They call the default constructor. Define the enumeration trafficlamp to implement the ordinary next method to implement the abstract next method: each element is an instance object generated by the subclass of the enumeration class, which is defined in a way similar to the internal class. When only one enumeration member is added in the constructor with a method, it can be used as a singleton implementation method.

Chapter 3 reflection

  1. The cornerstone class of reflection
    Comparison question: the person class representative, its instance object is Zhang San, Li Si, such a specific person, each Java class in the Java program belongs to the same class thing, the Java class name that describes such things is class. Comparison question: what kind of representation does most people use? Which of the following classes can be used to list many Java classes? The person Java class. Class class represents the Java class. What are the corresponding instance objects? It corresponds to the bytecode of each class in the memory, such as The Byte Code of the Person class and the byte code of the arraylist class. A class is loaded into the memory by the class loader and occupies a storage space. The content in this space is the class bytecode. the bytecode of different classes is different, so their content in the memory is different. The space can be represented by objects respectively. These objects obviously have the same type. What is this type? How to obtain the Instance Object (class type) class name corresponding to each bytecode. class, for example, system. class Object. getclass (), for example, new date (). getclass () class. forname ("Class Name"), for example, class. forname ("Java. util. date "); nine predefined class instance objects:
    See the help Int. Class = integer. Type class. isarray () of the class. isprimitive method ()

The class instance objects of the array type all have their own class instance objects, for example, int [], void...

  1. Reflection
    Reflection maps various components in the Java class into corresponding Java classes. For example, a Java class is represented by an object of A Class class, and the components of a class: member variables, methods, constructor methods, packages, and other information are also represented by Java classes, just like a car is a class, the engine and gearbox in a car are also a class. It indicates that the class of the Java class obviously needs to provide a series of methods to obtain information such as variables, methods, constructor, modifier, and package, these messages are represented by instance objects of corresponding classes, such as field, method, contructor, and package. Each member of a class can be represented by an instance object of the corresponding reflection API class. After you call the class method to obtain these instance objects, what is the use of these instance objects? How to use it? This is the key point of learning and application anti-attack.
  2. Constructor class
    The constructor class represents a constructor in a class to obtain all constructor methods of A Class: Example: constructor [] constructors = Class. forname ("Java. lang. string "). getconstructors (); get a constructor = Class. forname ("Java. lang. string "). getconstructor (stringbuffer. class); // you need to use the type to create an instance object when getting the method:

Common method: String STR = new string (New stringbuffer ("ABC"); Reflection Method: String STR = (string) constructor. newinstance (New stringbuffer ("ABC"); // class of the Instance Object of the same type above is used to call the obtained method. newinstance () method:
Example: String OBJ = (string) class. forname ("Java. lang. string "). newinstance (); this method first obtains the default constructor, and then creates an Instance Object using this constructor. How is the code written in this method written? The cache mechanism is used to save the instance objects of the default constructor.

  1. Field Class
    The field class represents a member variable in a class. This example uses eclipse to automatically generate a Java class constructor. The resulting Field object corresponds to the member variable above the class, or is it the member variable corresponding to the object? There is only one class, and there are multiple instance objects in this class. If it is associated with an object, which object is associated? Therefore, fieldx represents the definition of X, rather than the specific X variable. Sample Code:
    Reflectpoint point = new reflectpoint (1, 7 );
    Field y = Class. forname ("cn. itcast. corejava. reflectpoint"). getfield ("Y"); system. Out. println (Y. Get (point ));
    // Field x = Class. forname ("CN. itcast. corejava. reflectpoint "). getfield ("X"); field x = Class. forname ("CN. itcast. corejava. reflectpoint "). getdeclaredfield ("X"); X. setaccessible (true); system. out. println (X. get (point); job: Change "B" in the string content of all string-type member variables of any object to ""
  2. Method class
    Method charat = Class. forname ("Java. Lang. String"). getmethod ("charat", Int. Class); Call method:
    Common method: system. Out. println (Str. charat (1 ));
    Reflection Method: system. out. println (charat. invoke (STR, 1); what does it mean if the first parameter of the invoke () method passed to the method object is null? This method object corresponds to a static method! Differences between jdk1.4 and jdk1.5 invoke Methods: jdk1.5: Public object invoke (Object OBJ, object... ARGs) jdk1.4: Public object invoke (Object OBJ, object [] ARGs), that is, when an array needs to be passed as a parameter to the invoke method according to the jdk1.4 syntax, each element in the array corresponds to a parameter in the called method. Therefore, the code that calls the charat method can also be changed to charat by using jdk1.4. invoke ("STR", new object [] {1}) format.
  3. Execute the main method in a Class Using Reflection
    Objective: To write a program that can execute the main method in the class based on the class name provided by the user. After the call is completed in normal mode, you need to understand why the call should be performed in reflection mode?
    Problem:
    The parameter used to start the main method of the Java program is a string array, that is, public static void main (string [] ARGs). When the main method is called through reflection, how do I pass PARAMETERS FOR THE invoke method? According to the jdk1.5 syntax, the entire array is a parameter, and according to the jdk1.4 syntax, each element in the array corresponds to a parameter. When a string array is passed as a parameter to the invoke method, which syntax does javac use? Jdk1.5 must be compatible with the jdk1.4 syntax and will be processed according to the jdk1.4 syntax, that is, the array is split into several separate parameters. Therefore, when passing parameters to the main method, the Code mainmethod cannot be used. invoke (null, new string [] {"XXX"}), javac only understands it as the jdk1.4 syntax, instead of interpreting it as the jdk1.5 syntax, the parameter type is incorrect. solution: mainmethod. invoke (null, new object [] {New String [] {"XXX"}); mainmethod. invoke (null, (object) New String [] {"XXX"});, the compiler performs special processing and does not treat parameters as arrays during compilation, in this case, the array will not be split into several parameters.
  4. Array reflection
    Arrays with the same dimension and element type belong to the same type, that is, they have the same class instance object. The returned parent class of the getsuperclass () method of the array class instance object is the class corresponding to the object class. Basic Types of one-dimensional arrays can be used as objects, but not as objects []. Non-basic types of one-dimensional arrays can be used as objects, arrays can also be used as the object [] type. aslist () method for int [] and string. the array tool class is used to perform array reflection. Question: How can we get the element type in the array? The basic data type is not an object. The object is used for one-dimensional data.
    Use array reflection to operate the array. You can know its length.
  5. Functions of reflection implementation framework
    Core issues to be addressed by frameworks and frameworks
    I made a house for sale to users. Users Installed doors and windows and air conditioners themselves. My house was a framework. users needed to use my framework and insert the doors and windows into the framework I provided. The framework is different from the tool class. The tool class is called by the user class, while the framework is called by the user.
    Core issues to be addressed by the Framework
    When I am writing a framework (house), you may still be in elementary school and will not write programs yet? I wrote.
    Comprehensive Cases
    How can a framework program call the classes (doors and windows) You will write in the future? Because you cannot know the name of the class to be called when writing a program, you cannot directly create an instance object of a class in the program. Instead, you must use the reflection method.
    First, use the new. Statement to create the arraylist and hashset instance objects. This example uses eclipse to automatically generate the equals and hashcode methods of the reflectpoint class and compare the running results of the two sets. Then, create the instance objects of arraylist and hashset by using the configuration file and reflection, and compare and observe the running results. Elipse is introduced to explain how to manage resource files.

 

 

Chapter 4: Generic

  1. Understanding generics
    Arraylist <E> class definition and arraylist <integer> class reference involve the following terms:
    E In the entire arraylist <E> generic arraylist <E> is called a type variable or a type parameter. The entire arraylist <integer> is called a parameterized type. The integer in arraylist <integer> is called a type parameter. <> In the instance or the actual type parameter arraylist <integer>, you can refer to an object of the original type as the primitive type parameterized type, compile report warning, for example, collection <string> C = new vector (); // is it OK, isn't it just a sentence for the compiler? The original type can reference an object of parameterized type and compile a report warning. For example, collection C = new vector <string> (); // the original method accepts a set parameter, the new type must be passed in to the vector <string> V = new vector <Object> (); // error! /// If you do not write <Object>, yes. If you write it, the vector <Object> V = new vector <string> (); // It is also incorrect.
    Compatibility between parameterized types and original types
    Parameterized types do not consider the inheritance relationship of type parameters: the compiler cannot create arrays of generic variables. That is, when creating an array instance, the array elements cannot use parameterized types. For example, the following statement has an error:
    Vector <integer> vectorlist [] = new vector <integer> [10];
    Question: Will the following code report an error?
    Vector V1 = new vector <string> (); vector <Object> V = V1;
  2. In generics? Wildcard
    Define a method to print all data in a set of any parametric types. How can this method be defined? Error Method:
    Public static void printcollection (collection <Object> Cols)
    {For (Object OBJ: Cols ){

System. Out. println (OBJ);}/* cols. Add ("string"); // Yes, cols = new hashset <date> (); // an error is reported! */}
Correct method:
Public static void printcollection (collection <> Cols) {for (Object OBJ: Cols) {system. out. println (OBJ);} // cols. add ("string"); // error, because it does not know its future match must be string cols. size (); // yes,
This method has no relationship with the type parameter Cols = new hashset <date> ();}
Summary:
Wildcards can be used to reference various other parameterized types. variables defined by Wildcards are mainly used as references. Methods irrelevant to parameterization can be called, and methods related to parameterization cannot be called.

  1. In generics? Wildcard Extension
    Upper boundary of a wildcard: Specify the lower boundary of a wildcard. Note:
    Correct: vector <extends number> X = new vector <integer> ();
    Error: vector <extends number> X = new vector <string> ();
    Correct: vector <super integer> X = new vector <number> ();
    Error: vector <super integer> X = new vector <byte> (); Wildcards are always included. It can only be used as a reference and cannot be used to assign values to other variables. Vector <extends number> Y = new vector <integer> (); vector <number> X = y; The above code is incorrect, the principle is similar to that of vector <Object> X11 = new vector <string>. values can only be assigned by force type conversion.
  2. Comprehensive case of generic collection classes
    Writing the following code means you have mastered Java's generic collection classes.
    Hashmap <string, integer> Hm = new hashmap <string, integer> ();
    Hm. Put ("zxx", 19 );
    Hm. Put ("lis", 18 );
    Set <map. Entry <string, integer> MEs = hm. entryset (); For (Map. Entry <string, integer> me: MEs ){
    System. Out. println (Me. getkey () + ":" + me. getvalue ());
    }
    Perform an iteration on the set or map set on the JSP page: <C: foreach items = "$ {map}" Var = "entry" >$ {entry. key}: $ {entry. value} </C: foreach>
  3. Define generic methods:
    Java generic methods do not have powerful C ++ template functions. The following code in Java cannot be compiled:
    <T> t add (t x, t y) {return (t) (x + y); // return NULL ;}
    The angle brackets used to place generic type parameters should appear after all the modifiers of the method and before the return type of the method, that is, before the return value. By convention, type parameters are usually represented by a single uppercase letter.
    Syntax of the generic method for exchanging the positions of two elements in an array is defined as follows:
    Static <E> void swap (E [] A, int I, Int J)
    {E t = A [I]; A [I] = A [J]; A [J] = T;} // or use an interview question: reversing the order of elements in an array:
    Only the reference type can be used as the actual parameter of the generic method. Swap (New int [3], 3, 5); the statement reports a compilation error. In addition to the extends qualifier, you can also use the extends qualifier when defining generics, for example, the definition of the class. getannotation () method. You can use & to specify multiple boundaries, such as <v extends serializable & cloneable> void method () {} generic methods, constructor methods, and static methods. You can also use type variables to indicate exceptions, which are called parameterized exceptions. They can be used in the throws list of methods, but not in catch clauses. You can have multiple types of parameters in the generic type. Separate them with commas (,) in the angle brackets. For example, public static <K, V> V getvalue (K key) {return map. get (key );}
  4. Exercise questions of generic methods
    Compile a generic method to automatically convert objects of the object type to other types. Define a method to fill all elements in an array of any type into an object of the corresponding type. You can use a custom generic method to print all content in a set of any parameterized types. In this case, the wildcard scheme is more effective than the normal method. When a type variable is used to express the relationship between two parameters or between parameters and return values, that is, the same type variable is used in the method signature, or the type variable is also used in the method body code, rather than only used in the signature. Define a method to securely copy data from a set of any parameter types to an array of the corresponding type. Define a method to securely copy data from an array of any parameter type to another array of the corresponding type.
  5. Type inference of type parameters
    The process for the compiler to determine the actual type parameter of the model method is called type inference. The type inference is relative to perceptual inference, and its implementation method is a very complicated process. The rule is as follows:
    When a type variable is only applied to one of all parameters and return values in the entire parameter list, it is determined based on the actual application type at the time of calling the method, this is easily inferred by feeling, that is, the type of the generic parameter is directly determined based on the type or return value of the parameter passed when the method is called, for example: swap (New String [3], 3, 4) static <E> void swap (E [] A, int I, Int J) when a type variable is applied in multiple parameters and return values in the entire parameter list, if multiple real application types correspond to the same type when calling the method, it is easy to infer from the feeling, for example: add) static <t> t add (t a, t B) when a type variable is applied to multiple parameters and return values in the entire parameter list, if multiple actual application types correspond to different types when calling a method, and no return value is used, the maximum intersection type among multiple parameters is used. For example, the actual type of the following statement is "Number". Compilation is okay, but there is a problem during running: Fill (new integer [3], 3.5f) static <t> void fill (T [] A, t v) when a type variable is applied to multiple parameters and return values in the entire parameter list, if multiple actual application types correspond to different types and return values are used when calling a method, the type of return values is given priority. For example, the actual type of the following statement is integer, compile the report error, change the variable X type to float, compare the error message reported by eclipse, and then change the variable X type to number. No error occurs: int x = (3, 3.5f) the type inference of the static <t> t add (t a, t B) parameter type is passed. In the first case below, it is inferred that the actual parameter type is object and there is no compilation problem, in the second case, the type variable is directly determined to be of the string type based on the parameterized Vector class instance. The compilation will fail: Copy (new integer [5], new string [5]) static <t> void copy (T [] A, T [] B); copy (new vector <string> (), new integer [5]) static <t> void copy (collection <t> A, T [] B );
  6. Define generic types
    If the same generic parameter is used in multiple instance objects of the class, that is, when the generic type referenced in these areas must be the same actual type, in this case, the generic type is used for definition, that is, the generic type at the class level. The syntax format is as follows:
    Public class genericdao <t>
    {Private t field1; Public void save (t obj ){}
    Public t getbyid (int id ){}}
    Class-level generic variables are parameterized Based on the type information specified when the class name is referenced. For example, you can genericdao <string> Dao = NULL in either of the following ways; new genericdao <string> ();
    When you parameterize a generic type, the instance of the type parameter must be a reference type, not a basic type. When a variable is declared as a generic type, it can only be called by instance variables, methods, and internal classes, rather than static variables and static methods. Because static members are shared by all parameterized classes, static members should not have class-level type parameters.
    Q: Is there only one method in a class that requires generics? Is it class-level generics or method-level generics?
  7. Generic inheritance
    During inheritance, the type parameters of the generic parent class are not instantiated.
    Code
  8. Obtain generic parameterized types through reflection
    Sample Code:
    Class genericalreflection {
    Private vector <date> dates = new vector <date> ();
    Public void setdates (vector <date> dates) {This. Dates = dates ;}
    Public static void main (string [] ARGs ){
    Method methodapply = genericalreflection. Class. getdeclaredmethod ("applygeneric", vector. Class); parameterizedtype ptype = (parameterizedtype) (methodapply. getgenericparametertypes () [0];
    System. out. println ("setdates (" + (class) ptype. getrawtype ()). getname () + "<" + (class) (ptype. getactualtypearguments () [0]). getname () + "> )");}
    }
    Application of generic Dao:
    Public abstract class daobaseimpl <t> implements daobase <t> {
    Protected class <t> clazz; Public daobaseimpl () {type = This. getclass (). getgenericsuperclass (); parameterizedtype Pt = (parameterizedtype) type; this. clazz = (class) pt. getactualtypearguments () [0]; system. out. println ("clazz =" + this. clazz );}}
    Public class articledaoimpl extends daobaseimpl <Article> implements articledao {}

 

Chapter 5: class loaders and their proxies

  1. Class Loader
    This section briefly introduces the functions of classloaders and classloaders. Multiple classloaders can be installed in Java virtual machines. By default, the system has three major classloaders, each class is responsible for loading classes at a specific location: Bootstrap, extclassloader, and appclassloader class loaders are also Java classes, because other class loaders of Java classes are also loaded by the class loaders, obviously, the first class loader must be not a Java class, which is exactly Bootstrap. All class loaders in the Java Virtual Machine are organized in a tree structure with parent-child relationship. when instantiating each class loader object, you need to specify a parent class loader object for it or use the system class loader as its parent class by default.
  2. Parent-child relationship and jurisdiction dimensions between class loaders

Chapter 6: Concurrent thread Library

    1. Review of traditional thread Mechanism
      The two traditional methods for creating a thread are to compile the Running code in the run method covered by the thread subclass, and to compile the code summary in the run method of the runnable object passed to the thread object: check the source code of the run () method of the thread class. We can see that both methods involve a previous knowledge point: Can I throw an interruptedexception exception on the run method declaration, in order to omit the internal thread of the run method. try… of the sleep () Statement... Catch processing. call the run method of the thread object. If the run method of the thread class is not overwritten and a runnable object is set for the thread object, the run method calls the run method of the runnable object. Problem: If the run code is written in the run method covered by the thread subclass and a runnable object is passed to the thread sub-class object, when the thread is running, is the Execution Code of the sub-class run method? Or the code of the run method of the runnable object? Previous knowledge points involved: how to call the non-default constructor of the parent class by constructing anonymous internal class objects.
    2. Timer application Timer class timertask class
      Timer application Timer class timertask class
    3. Synchronization mutex and communication of threads
      Use the synchronized code block and Its Principle to analyze the synchronization monitor object used by the static method using the synchronized method? Wait and notify implement inter-thread communication.
      How multiple threads access shared objects and Data
      If the code executed by each thread is the same, you can use the same runnable object, which contains the shared data. For example, the ticket buying system can do this. If the code executed by each thread is different, different runnable objects need to be used. There are two ways to achieve data sharing between these runnable objects: encapsulate the shared data in another object, and then pass the object to each runnable object one by one. The operation method of each thread to share data is also allocated to the object to complete, so that it is easy to implement the mutex and communication of each operation on the data. These runnable objects are used as internal classes in a class, and shared data is used as member variables in this external class. Each thread also allocates operations on shared data to external classes, in this way, operations on shared data are mutually exclusive and communicated. As runnable objects of internal classes, these methods of external classes are called. The combination of the above two methods: encapsulate the shared data in another object, and each thread's operation method on the shared data is also allocated to the object to complete, an object acts as a member variable in this external class or a local variable in the method. The runnable object of each thread acts as a Member internal class or a local internal class in the external class. In short, it is best to put several pieces of code that need to be synchronized and mutually exclusive in several independent methods, and then put these methods in the same class, which makes it easier to implement synchronization and mutual exclusion and communication between them. An extreme and simple way is to define a static variable in any class, which will be shared by all threads.
    4. Threadlocal implements shared variables within the thread range
      See the following and auxiliary code to explain the role and purpose of threadlocal: To achieve data sharing within the thread, that is, for the same program code, multiple modules share one copy of data when running in the same thread, while other modules share another copy of data when running in another thread. Each thread calls the Set Method of the global threadlocal object, which is equivalent to adding a record to its internal map. The key is the respective thread, and the value is the value transmitted by the respective set method. You can call the threadlocal. Clear () method at the end of a thread to release the memory more quickly. You can do this without calling it, because the threadlocal variable can be automatically released after the thread ends. Threadlocal Application Scenario: order processing involves a series of operations: reducing inventory, adding a flow account, and modifying the General Ledger. These operations must be completed in the same transaction, this is usually done in the same thread. If the accumulation of company receivables fails, roll back the previous operations. Otherwise, submit all operations, this requires that these operations use the same database connection object, and the code of these operations is located in different module classes. Bank transfers include a series of operations: to reduce the balance of the transferred account and increase the balance of the transferred account, the two operations must be completed in the same transaction, they must use the same database connection object, the transfer-in and transfer-out operations code are two different account object methods. For example, in the actioncontext of strut2, when the same code is called and run by different threads, the data operated by this code is the respective States and data of each thread. For different threads, the objects obtained by the getcontext method are different. For the same thread, no matter how many times the getcontext method is called or in which module the getcontext method is called, the same object is obtained.
      Experiment case: define a global shared threadlocal variable, start multiple threads to store a random value in the threadlocal variable, and then each thread calls methods of other classes, read the threadlocal variable value from the methods of these classes, and you can see that multiple classes share the same data in the same thread. Encapsulate the threadlocal variable so that the outside world does not directly operate the threadlocal variable. It is rare to encapsulate basic data. It is common to encapsulate data of object types, that is, to allow a class to create an independent instance object for different threads.
    5. Shared data within the thread range
      Data bound to thread 1
      Object and module
      Object and Module B
      Object and Module C
      Thread 1 variable or expression
      Thread 2
      Data bound to thread 2
    6. Concurrent thread library in Java 5
      The Java. util. Concurrent package and the sub-package API help document the java. util. Concurrent. Atomic package. The following describes how to quickly understand the meaning of the atomic package through the following two methods.
      To explain the role of the volatile type, check the Java language specification. Boolean compareandset (expectedvalue, updatevalue) of the atomicinteger class; int addandget (int I, int delta) of the atomicintegerarray class; Java. util. Concurrent. Lock
      The concept of thread pool and executors class applications create a fixed size thread pool create cache thread pool create a single thread pool.
    7. Thread Pool
      The concept of thread pool and the application of the executors class can be used in three ways: creating a fixed-size thread pool, creating a cache thread pool, and creating a single thread pool.
      Close the thread pool:
      Comparison between shutdown and shutdownnow
      Start timer with Thread Pool
      Call scheduledexecutorservice's schedule method. The returned schedulefuture object can cancel the task. It supports the time interval for repeated tasks. Absolute Time is not directly supported and must be converted to relative time.
    8. Callable & Future
      The result type returned by future must be the same as that returned by callable. This is achieved through generics. Callable must be submitted using the submit method of executorsevice. The returned future object can cancel the task. Completionservice is used to submit a set of callable tasks. Its take method returns the future object of a completed callable task. For example, I planted wheat in several places at the same time and waited for the harvest. When harvesting, it is the first mature, then the first wheat to be harvested.
    9. Lock & condition for Synchronous thread Communication
      The lock method is more object-oriented than the Synchronized Method in the traditional thread model. Similar to the lock in life, the lock itself should also be an object. The code snippets executed by two threads must use the same lock object to implement synchronization and mutual exclusion. Read/write locks: read/write locks are divided into read/write locks. Multiple read locks are not mutually exclusive. The read/write locks are mutually exclusive and are controlled by the JVM. You only need to apply the corresponding locks. If your code read-only data can be read by many people at the same time but cannot be written at the same time, read the lock. If your code modifies data, only one person can write it, and cannot be read at the same time, then write the lock. In short, read locks are applied during reading and write locks when writing! While waiting for condition, "false awakening" is allowed, which is usually used as a concession to the basic platform semantics. For most applications, this has little practical impact, because condition should always be waited in a loop and testing the State declaration being waited. An implementation can remove possible false wakeup at will, but it is recommended that application programmers always assume that these false wakeup may happen, so they always wait in a loop. A lock can have multiple conditions, that is, multiple waits and notifications. For more information, see the application cases of blocking queues implemented by lock and condition provided by jdk1.5. In addition to the algorithm, we also need to understand the object-oriented encapsulation. In the traditional thread mechanism, a monitor object can only have one channel of waiting and notification. To realize multiple ways of waiting and notification, multiple synchronous monitor objects must be nested. (If only one condition is used, the two are waiting. Once one is put in, the notification may cause the other to put and go down .)
    10. Semaphore signal lights
      Semaphore can maintain the number of threads currently accessed and provide a synchronization mechanism. You can use semaphore to control the number of threads simultaneously accessing resources. For example, you can implement the number of concurrent threads allowed by a file. The functions implemented by semaphore are similar to five pitfall in the restroom. If there are ten people who want to go to the restroom, how many people can go to the restroom at the same time? At the same time, only five people can occupy the resources. When one of the five people gives up, one of the other five waiting for the resources can occupy the resources. In addition, among the five waiting persons, the opportunity can be obtained at random or in the order of first come and then, depending on the parameter options passed in when the semaphore object is constructed. The semaphore object of a single semaphore can implement the mutex lock function, and the lock can be obtained by one thread, and then released by another thread ", this can be applied to deadlock recovery.
    11. Other synchronization tools
      Cyclicbarrier
      It indicates that everyone is waiting for each other. After the gathering, everyone starts to set up and meet at the designated place after the scattered activities. This is like the staff of the entire company taking advantage of the weekend outing, first, start from their home to the company, and then start to play in the park at the same time, gather at the designated place and then start dining at the same time ,...
      Countdownlatch
      As if a countdown counter, the countdownlatch object's countdown method is called to reduce the counter by 1. When the Count reaches 0, all the waiting persons or individual waiting persons start to execute. This directly demonstrates the role of countdownlatch through code, so that students can better understand it. One person (or multiple people) can be implemented, and wait for everyone else to inform him. This is like a plan that requires signatures from multiple leaders before further implementation. The effect of notifying multiple people by one person can also be achieved. Similar to a referee's password, athletes start to run at the same time. It's good to use this function to make a hundred-meter race!
      Exchanger
      It is used to exchange data between two people. After a transaction is completed, each person wants to exchange data with the other party. The first person who obtains the data will wait until the second person receives the data, in order to exchange data with each other.
    12. Blocked queue
      What is a blocking queue? What is the function of blocking a queue? What is the implementation principle of blocking a queue.
      The blocking queue is similar to semaphore, but it is also different. The blocking queue column stores data on one side, and the other releases data. semaphore usually sets and releases semaphores on the same side.
      Arrayblockingqueue
      Only the put and take methods have blocking functions. A queue with three spaces is used to demonstrate the functions and effects of blocking queues. Use two queues with one space to synchronize notifications.
    13. Synchronization set
      For more information about the concurrent access of traditional collection classes, see appendix. in the traditional way, use the synchronizedcollection method provided by the collections tool class to obtain the synchronization set and analyze the implementation source code of this method. Collection in the traditional mode cannot be modified when the collection is iterated. Use the synchronized thread questions of the Apsara stack interview to demonstrate the source code of the checkforcomodification method of javasactlist and analyze the causes of concurrentmodificationexception.
      Java 5 provides the following synchronization collection classes:
      By reading the description in the Java. util. Concurrent package, you can know which concurrent sets are available. concurrenthashmap copyonwritearraylist copyonwritearrayset

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.