J2SE Getting Started:
Preliminary knowledge
2. Storage mode and operation control
3. Object-oriented technology
4. Common data structure
5. Abnormal processing mechanism
6. Image processing and audio operation
7. Tiantian interface (SWING)
8. Multi-threaded technology
9. I / O operation
10. Basic network technology
Preparatory knowledge:
(1) The historical background of Java is not to say more.
(Ii) Environment variable settings and principles
The first step of developing the Java program must set the environment variable, which mainly includes the setting of Path and ClassPath, understanding the role of Path and ClassPaths for the Java program.
PATH: When operating a certain command, the operating system will search by Path; if you add some of Java's tools such as Java, JavaC, Javadoc, etc., you can search when you run a Java compiler or interpreter. These tools are implemented, and these tools are in the bin directory under the JDK directory.
The setting of PATH is as follows (set the JDK in C: /J2SDK1.4.2):
Path =% path%; C: /J2SDK1.4.2/bin;
Note:% PATH% indicates that the original PATH path is reserved, or the JDK path directly below the original Path path directly. ; Separation under Windows (Linux is :).
ClassPath: For a path list, the class used to search for Java compilation or runtime. The virtual machine is searched in the following order and load all the needs:
Guide class: Composition of the Java platform, including the classes in rt.jar and i18n.jar.
Extended class: Use the Java extension mechanism that is located in the extended directory ($ java_home / jre / lib / ext). JAR file package.
User Class: Developer defined classes or third-party products that do not use Java extension mechanisms.
The set of ClassPath is as follows:
Classpath = .; c: /j2sdk1.4.2/lib/tools.jar; c: /j2sdk1.4.2_05/jre/lib/rt.jar
Note: Represents the current directory, if you think this catalog is too cumbersome, you can set a java_home first, and let java_home = c: /j2sdk1.4.2/, then set the classpath format:% java_home% lib / Tools.jar et al. Yes. Dt.jar is about the class library of the operating environment, Tools.jar is the class library about some tools.
Precautions:
Program and class
There can be only one public class in the Java source program, but there can be any ordinary class, and this program file name must be the same as the class name of the public class.
Package operation
Generally, it is convenient to manage the Java classes into one file, and then put it in a package, that is, a package contains several classes including the primary and common classes. The program format that runs compiled is:
Java package name. Main product name
Coding habit
During the Java development process, it is necessary to develop good coding habits (to grab ^ ^) from dolls, such as writing to see the identifier, code indent format, standard and detailed notes, etc.
Storage mode and operation control
The so-called storage mode and operation control is actually the selection and algorithm of the data structure. The ability to write more this area will naturally improve.
(1) The storage method refers to the data type of Java, which is also important in the selection of variables in program design, and should be considered as much as possible in case requirements.
Simple data types include:
Integer: Byte, Short, Int, Long
Floating point type (floating): Float, Double Character Type (Textual): char
Boolean type (Logical): Boolean
Composite data types include:
String Type: String
Array
Class
Interface
(Ii) Operation method mainly refers to the sequence, transfer, and cycle of the program design. Regardless of the complex procedures, these control statements are separated. Therefore, proficiency is mastered to use the statement to write a beautiful and efficient code.
Sequential execution
Condition transfer
I if (exp) {
} else (eXP) {
}
II Switch (exp) {
Case?: Break;
Case?: Break;
.......
DEFAULT: BREAK;
}
Cyclic operation
I for (;;) {
}
II While (exp) {
}
Jump instruction
I Break;
II CONTINUE;
III Return;
Note:
Some techniques can be employed in operation: If the judgment end condition can be set to the type of dead cycle (such as while (TRUE)), set the condition BREAK in the block.
BREAK and Continue Difference: The BREAK statement is a block that is jumped out of its specified, and no longer performs the determination of the termination condition, and is executed at the first statement that keeps up with the block; the Continue statement is used to end this cycle, skip cycle The following statements have not yet been executed below, followed by the determination of the termination condition to determine whether to continue cycling.
Object-oriented technology
Oo is a deep thought and is also a common idea of modern software design. There are many priorities in OO summary, which should be used as much as possible. For example, priority use of class aggregation rather than inheritance, programming for interface, stroning high cohesion, etc. The first chapter in the "Design Mode Exercise" book is very good for OO and design patterns, and speak deeply. General OO and design mode cooperate with software design to play an unexpected effect, so recommend OO and design mode together, and introduce a Bible design pattern of the design pattern - can be used for object-oriented software Basics (although it is implemented with C , but the ideological and language is not related to the language), the 23 models introduced in the book are refined extraction of some solutions in the past software development, which is refreshing and worth reading.
(I) OO Basic Thought is to use basic concepts such as classes, objects, inheritance, packages, messages.
Basic characteristics are encapsulation, inheritance, polymorphism:
Captive: Binds the properties and operation of the object into an entity, to hide the internal details, and only provide the interface to the class user. The basic principle is not an external member variable, while providing a set, a GET method for accessing member variables using the characteristics of Beans.
Inheritance: It is not necessary to accurately attribute to the parent class with a common, sub-class feature, such as the passenger period is a special class of ships and passenger transportation tools, and the ship is a parent class, and the passenger is a subclass of the passenger function.
Polymorphism: The polymorphism of the object refers to the attributes or services defined in the general class, which can have different data types or different behaviors. Such as: "Draw" method, "elliptical" and "polygon" of "Geometry" are subclasses of "geometric map", and its "drawing" method is different.
(Ii) Key technology:
Class, object
The relationship between classes and objects is like the relationship between the mold and castings.
Class declaration:
[PUBLIC] [Abstract | Final] class classname [extends superclassname] [IMPLEments Interfacelist] {
Member variables;
Member method;
}
Member variables:
[public | protected | private] [static]
TYPE VARIABLENAME;
The meaning of the defined words in the variable declaration:
Static: Static variable (class variable); relative to instance variables
Final: constant
Transient: Temporary variables for object archives
Volatile: Contribute variables for concurrent threads
Member method:
[public | protected | private] [static]
[femAl] [native] [synchronized]
Returntype methodname ([paramlist]) [THROWS EXCEPTIONLIST] {Statements}
The meaning of the defined words in the method statement:
static: Class method, can be directly called by class name
Abstract: Abstract method, no method, realized by subclass
Final: The method cannot be rewritten
Native: Integrated different language code
Synchronized: Controlling access to multiple concurrent threads
Limit words in the class:
Private
A member defining a private in the class can only be accessed by this class itself. If a class constructor is declared as Private, other classes cannot generate an instance of this class.
DEFAULT
A member that does not add any access rights defined by the class belongs to the default access state, which can be accessed by this class itself and the class in the same package.
protected
The class is defined as a member of Protected, which can be accessed by this class itself, its subclass, its subclass (including subcategories in the same package) and all other classes in the same package.
public
The class is limited to members of public, and can be accessed by all classes
Construction method:
The constructor is a special method. Each class in Java has a constructor to initialize an object of the class. The constructor has the same name as the class name, and does not return any data type.
Overload is often used in the construction method. The constructor can only be called by the New operator.
Method Overload and method rewrite:
Method Overload refers to multiple methods to enjoy the same name, but the parameters of these methods must be different, or the number of parameters is different, or the parameter type is different. The return type cannot be used to distinguish the method of overload.
Method rewrite refers to the method of parentians with inheritance relationships. The method of the same name, the method of rewriting in the subclass, and the method of rewritten in the parent class must have the same name. The same parameter table and the same return type, only The function is different. The Java runtime system determines which method called according to the instance calling the method. An example of a subclass, if the subclass rewrites the method of the parent class, the method of running the subclass when the system is runtime; if the subclass inherits the method of the parent class (not rewriting), the runtime system calls the parent class. Methods.
The principles should follow when rewriting:
1) After rewriting the method, it is not more stringent access to the objective method (which can be the same).
2) Remote method does not have more exceptions to the method of rewriting.
Note: Overloading the same name method for the same class, rewriting the same name method for the parent son class with inheritance relationship.
Commonly used keywords
1) static
Static Variable: All such instances share this static variable, that is, only one storage space is assigned, all such objects can be manipulated. Static method: This method can be called without this class, calling a static method is "Classification. Method Name".
Static Class: Usually a normal class is not allowed to be static, only one internal class can be. At this time, this statement is that the static internal class can be used directly as a normal class without an example of an external class.
2) Final
Final member: It is not variable for basic types, and the reference is not changeable for object variables. Initialization can be in two places, one is its definition, that is, directly assigning it directly when the final variable is defined, and the other is in the constructor. These two places can only be selected, either giving value during defining, or give value in the constructor, not only giving value at the time of defining, and give additional values in the constructor.
Final method: State the method as Final, then explain that the features you already know this method have met you, do not need to expand, and do not allow any classes from this kind of inheritance to override this method, but inherit can still Inherit this method, that is, it can be used directly.
Final class: Final class is almost no different from the ordinary class, but it has lost the feature of the inheritance.
3) Super, THIS (commonly used in construction methods)
SUPER usage:
Visiting the parent class hidden member variables, such as:
Super.variable;
Call the way to rewritten in the parent class, such as:
Super.method ([paramlist]);
Call the constructor of the parent class, such as:
Super ([paramlist]);
This typically refers to the current object, and Super is usually referring to a secondary class. In the construction method, the super parameter is used to call the same form of constructor in the parent class; the THIS will be sent to the constructor of the current same parameter.
Operational control
The generation of objects:
Disclaimer: The statement does not assign memory space for the object, but allocates a reference space; the object's reference is similar to the pointer, the 32-bit address space, its value points to a middle data structure, which stores information about the data type and The address where the current object is located, and the actual memory address in which the object is located is uncomfortable, which guarantees security. Instantiation: The operator NEW is assigned memory space, which calls the structure of the object, returns a reference; the different objects of a class occupy different memory spaces.
Object use:
Since the basic principle of encapsulation is to provide a member variable of the publication of the PUBLIC, it is generally only available to "." To reference the members of the class. The use of objects is actually transmitting messages to change certain attributes or perform certain operations.
Object clearance:
Java's garbage collector automatically scans the dynamic memory of the object, collects and releases the objects that are not referenced as garbage. System.gc (); when the system memory is exhausted or called System.gc () requires garbage collection threads to run synchronously with the system.
Inheritance (abstract class), interface
Abstract class:
Abstract Class AbstractClassClass {...} // Abstract class
Abstract Returntype AbstractMethod ([paramlist]) // Abstract method
The abstract class must be inherited, the abstract method must be rewritten. Abstract methods only need to declare, no need; abstract classes cannot be instantiated, abstract classes do not have to include abstract methods. If the class contains an abstract method, the class must be defined as an abstract class. interface:
[public] interface interface interfacename [extends listofsuperinterface] {...}
The interface is a kind of abstract class, only the definition of constants and methods, without the implementation of variables and methods, and its method is an abstract method.
Note:
A class can only use one inheritance relationship, but there can be multiple interfaces.
Abstract classes are "IS A" relationships, and the interface represents the "Like A" relationship. (Involved in design mode)
Internal class
Internal classes are classes in a class of internal nested classes, which can be a member of other classes, or within an internal definition of a statement block, or within an anonymous definition within an expression.
Anonymous class is a special internal class that contains a complete class definition (message response class, etc.) inside an expression.
Internal profession and shortcomings comparison:
◇ Advantages: Saving the size of the bytecode file generated after compiling
◇ Disadvantages: make the program structure unclear
Common data structure
Vector
ArrayList
List
Queue
Map
Tree
Stack
Hashtable
ENUMERATION
and many more. . .
Note: Generally, data acces in these data structures are objects objects, so the data removed from it is to be converted, and the other INT cannot be stored directly into these data structures, and the outer clask must be used (such as Integer Wait) to re-encapsulate to deposit.
On the one hand, Java is more likely to use, it should be that Java provides a rich data structure to users without letting users design a half-day data structure, and finally I have found it or have a mistake, depressed. Since Sun is well packaged well, just understand the features of these data structures and understand their interface methods.
Generally, you can get a help documentation in your study and development, but only the features of these data structures can be selected to choose the best data structure to develop excellent code.
Abnormal processing mechanism
Exceptions are actually an event in the program caused a normal instruction stream in the program.
All exceptions are directly or indirectly inherited in the Throwable class. Throwable is divided into two major subclass error and Exception, where Error is processed directly by virtual machines, and part of Exception is handled by the user.
Capture exception general framework:
Try {
......
} catch (exceptionname1 e) {
......
System.out.println ("Message:" E.GetMessage ()); //e.getMessage () is the method provided by THROWABLE to get information about exception events.
} catch (exceptionname2 e) {
......
E.PrintStackTrace (System.out); //e.printStackTrace () is used to track the contents of the stack when the exception event occurs.
}
......
} finally {
... // This part needs to be performed regardless of whether an exception is generated, unless system.exit (0)
}
When the Java runtime system gets an exception object, it will retrore the cylinder along the method to find the code that handles this exception. After finding the exception of this type of exception, the runtime system handles the current exception object to this method, which is called capture (CATCH).
Note: Capture the order of exceptions and the order of the CATCH statement. When the capture is captured, the remaining CATCH statement will no longer match. Therefore, when scheduled the order of the CATCH statement, first, the most special exception should be captured, and then gradually generalize. That is, it is generally arranged first, and then arrange the parent class. Throws with throw
Throw is a statement throw an exception, and throws is how an exception is thrown.
Throw: throw
THROWS: [
Declare to discard exception
If an exception is generated in one method, this method does not know how to process this exception event. At this time, a method should declare the except for abandonment, so that exceptions can spread from the calling stack Until the appropriate method captures it. The declaration discarding exception is indicated in the ThROWS clause in a method statement. E.g:
Public int ready () throws oException {
......
}
Throw exception
Exceptions are the process of generating exception objects, first generate exception objects, exceptions, or generated by virtual machines, or generated by certain classes, or generated in the program. In the method, the exception object is thrown through the Throw statement.
E.g:
IOEXCEPTION E = New IOException ();
Throw e; // artificially throwing abnormalities
Note: Throw is clearly throwing an exception to the upper layer; ThROWS is a variety of exceptions that may be thrown by a method.
Throws can be used alone, throw can't.
Customization
An exception is a class, user-defined exceptions must inherit from the Throwable or Exception class, it is recommended to use the Exception class.
Common abnormalities
ArithmeticException
ArrayIndexOutofBandSexception
ArrayStoreException
IOEXCEPTION
FilenotFoundException
NullPointerException
Malformedurlexception
Numberformatexception
OutofMemoryException
Image processing and audio operation
Image Processing
Java is not very powerful in desktop programs, so fewer uses of desktop programs, but this knowledge still needs to be understood. General image processing is divided into application in the application:
The images in the app are generally encapsulated into imageicon, which is attached to Button, Label, such as:
JButton btn = new jbutton ();
ImageICON IMG = New Imageicon (PATH);
btn.seticon (IMG);
The applet is generally used directly from the file from the file from the file, such as:
Image IMG = new image ();
IMG = GetImage (GetDocumentBase (), ImageFile;
...... ..
2D drawings are generally implemented in the applet, and is implemented by copying the Paint method. You can also get a graphics in your application to get a drawing handle. Specific translation, flipping, etc. is no longer described.
Note: In the AWT, it is generally used in Paint, swing, uses PaintComponent
Double buffer, sometimes the image will flash in the refresh, can be improved by double buffering. The double buffer is to create a drawing handle when the image is Update.
Audio operation
Audio operation and image processing are also similar, generally used in Applets, such as: audioclip first = getaudioClip (getDocumentbase (), "first.au");
First.PLAY ();
If you want to implement audio operations in your application, you can convert by applet, such as:
Audio Audio = Applet.newaudioclip (Audio_Path);
Audio.Play ();
Note: The audio operation of Java is very weak, generally only for playing audio files in formats such as MIDI, AU, and for MP3, if you want to play, there must be a decoder, but it is very disadvantageous (more complicated) .
Graphical interface (SWING)
Introduction to Swing
Swing is implemented by 100% pure Java, the Swing component is a light-weight component implemented by Java, no local code, does not rely on the operating system support, this is the greatest difference from the AWT component.
Swing uses a MVC design paradigm, "Model-View-Controller", where the model is used to save content, the view is used to display content, and the controller is used to control the user input.
Swing class hierarchy
In a javax.swing package, two types of components are defined: the top container (JFrame, Japplet, JDIALOG, and JWINDOW) and lightweight components. The Swing components are all direct subclasses and indirect subscms of the Container class of the AWT.
Java.awt.component
-java.awt.container
-java.awt.window
-java.awt.frame-javax.swing.jframe
-javax.dialog-javax.swing.jdialog
-javax.swing.jwindow
-Java.awt.Applet-javax.swing.japplet
-javax.swing.box
-javax.swing.jcomponet
MVC (Model-View-Control) Architecture
In an MVC user interface, three communication objects: models, views, and controls. The model is a specified logical representation, and the view is a visual representation of the model, and the control specifies how to handle user input. When the model changes, it notifies all views depending on its view, and the view uses the control to specify its corresponding mechanism. MVC is a general idea for making graphical user interfaces in existing programming languages, and its idea is to separate the content itself of the data and the display method so that the display of data is more flexible.
In the Swing component, the REGOSTERKEYBOARDACTION () method of the JComponent class can enable the user to replace the corresponding action of the SWING component on the mouse drive in the mouse drive.
Swings program structure
Swing programming generally follows the following procedures:
1. Introduced Swing package
2. Select "look and feel"
3. Set top container
4. Set buttons and labels
5. Add components to the container
6. Add a boundary around the component
7. Event processing
Classification of components:
Components can be divided into:
1 top container: JFrame, Japplet, JDialog, Jwindow total 4
2 Intermediate container: JPANEL, JSCROLLPANE, JSPLITPANE, JTOOLBAR3 special container: The intermediate layer of special role in GUI, such as JinternalFrame, JLAYEREDPANE, JROOTPANE.4 Basic Control: Realizing Interpersonal Interactive Components, such as JButton, Jcombobox, Jlist, JMenu, Jslider, JtextField.
5 Unbursible information Display: Displays components that cannot be editable information to users, such as Jlabel, JProgressBar, Tooltip.
6 Display of editable information: Displays the user with the formatted information that can be edited, such as Jcolorchooser, Jfilechoose, JFilechooser, JTable, Jtextarea.
The special features of the JComponent class are divided into:
1) Border setting: Use the setBorder () method to set the frame peripheral frame, using an EmptyBorder object to leave a blank around the component.
2) Double buffer: Use dual buffer technology to improve frequently changing components display effect. Unlike the AWT components, the JComponent component defaults double buffer, and does not have to rewrite the code. If you want to close the dual buffer, you can apply a setDoublebuffered (false) method on the component.
3) Tip information: Use the settooltext () method to set the prompt information to the user to the user.
4) Keyboard Navigation: Use the registerKeyboardAction () method to drive the components with the keyboard instead of the mouse. Sub-class AbstractButton for JComponent classes also provides a convenient way - using the setmnemonic () method to specify a character, and activate the button action through this character and a special modification of the current L & F.
5) Insert L & F: Each JComponent object has a corresponding ComponentUI object that completes all paintings, event processing, and decision size. The Componentui object relies on the current L & F that can be set with the UIManager.SetLookAndfeel () method to set the required L & f.
6) Support layout: By setting the maximum, minimum, recommended size method and setting X, Y alignment parameter value, specify the constraints of the layout manager, and supports the layout.
Basic rules using SWING
Unlike AWT components, Swing components cannot be added directly to the top container, which must be added to a content panel associated with the Swing top container. The content panel is a normal container contained in the top container, which is a lightweight component. The basic rules are as follows:
(1) put the SWING component into the content panel of a top Swing container
(2) Avoid using non-Swing heavyweight components.
There are two ways to add components to JFrame:
1) Use the getContentPane () method to get the content panel of JFrame, add it to the component: frame.getContentPane (). Add (childcomponent)
2) Establish an intermediate container such as JPanel or JDESKPApane to add components to the container, and set the container as the content panel of JFrame with the setContentPane () method:
JPanel Contentpane = New JPANEL ();
... // Add other components to jPanel;
Frame.setContentPane (ContentPane);
// Set the ContentPane object into the content panel of the Frame, various container panels and components
Root panel
The root panel consists of a glass panel, a content panel, and a selectable menu bar (JMenubar), while the content panel and the selectable menu bar are placed in the same layer. The glass panel is completely transparent, the default is invisible, providing a mouse event and a drawing on all components.
The root panel is provided:
Container getContentPane (); // Get content panel
SetContentPane (ContaN); // Setting the content surface
JMenuBar getmenubar (); // Active menu bar
SetMenubar (JMenubar); // Set the menu bar
JlayeredPane getLayeredPane (); // Get a layered panel
SetLayeredPane (JLAYEREDPANE); // Set the layered panel
Component getGlasspane (); // Get glass panel
Setglasspane (Component); // Set the glass panel
Facing panel
Swing provides two layered panels: JlayredPane and JDESKTOPPANE. JDESKTOPPANE is a subclass of JLayeredPane, which is set to accommodate the internal framework (JinternalFrame). Add components to a layered panel, which requires which layer to add it, indicate that the component is in this layer:
Add (Component C, Integer Layer, INT POSITION).
Scroll window (JScrollPane)
Splitter (JSPLITPANE)
Options board (JTabbedpane)
Toolbar (JToolbar)
Internal framework (JinternalFrame)
The internal framework jinternalframe is like a window inside the other window, which features the following characteristics:
1) The internal frame must be added to a container (usually JDESKTOPPANE), otherwise it is not displayed;
2) Do not need to call the show () or setvisible () method, the internal frame is displayed along with the container;
3) You must set the frame size with setsize () or pack () or setbounds method, otherwise the size is zero, the frame cannot be displayed;
4) You can use the setLocation () or setbounds () method to set the location of the internal frame in the container, the default value is 0,0, that is, the upper left corner of the container;
5) Like the top-level JFRAME, add components to the internal framework to add it on its content panel;
6) Create a dialog in the internal framework, you cannot use JDIALOG as a top window, you must use JOPANE or JINternalFrame;
7) The internal framework cannot listen to the window event, and can process the internal frame window by listening to the internal framework similar to the window event (jinternalFrameEvent).
Button (JButton)
Check box (JCheckbox)
Single selection box (JRADIOBUTTON)
Select box (JCOMBOBOX)
File selector (JFilechooser)
Tag (JLabel)
List (list)
Menu (JMenu)
JProgressBar sliding strip (JSLIDER)
Table (JTABLE)
JTREE
Layout manager
Although Swing has a top container, we cannot add the components directly to the top container, and the SWING form contains a contanet called the content panel, placing the content panel on the top container, and then adds the component into the content panel. The BoxLayout Layout Manager sequentially adds the components in order of the top and down (Y-axis) or from left to right (x-axis). To create a boxlayout object, you must indicate two parameters: the container and the spindle of the BoxLayout. By default, the components are aligned in the longitudinal axis direction.
The way to set the layout manager is as follows:
Pane.setLayout (New BoxLayout (PANE, BoxLayout.y-Axis);
The graphical interface needs to be understood, but it doesn't have to spend too much energy, because this knowledge update is too fast, and it is not mainstream technology. Recently, SWT has been happily, I don't know if Swing has become a new joy of developers. And with the development of development tools, the graphical interface will become very easy to use (not only do not do with Delphi), JBuider is doing well, so it is best to spend energy in other technologies, for graphics The beautification of the interface is used in need, and the personal point of view is used.
Multithreading technology
(1) Implementation
Thread class
Define a thread class, which inherits the thread THREAD and rewrites the method run (), at this time, the target target can be NULL when initializing the instance of this class, indicating that the thread body is executed by this instance. Since Java only supports single inheritance, the classes defined by this method cannot inherit other parent classes.
Direct inheritance THREAD class:
1) Cannot inherit from other classes;
2) Write simple, you can directly manipulate threads without using thread.currentthread ().
Runnable interface:
Provides a class that implements the interface runnable as a thread, when initializing a thread class or thread subclass thread object, transmit the target object to this thread example, and the thread body Run () is supplied by the target object. At this time, the class that implements the interface runnable can still inherit other parent classes.
Use the Runnable interface:
1) You can separate the CPU, code, and data to form a clear model;
2) You can also inherit from other classes;
3) Maintain the consistency of the program style.
example:
Thread T1 = New Mythread ("T1"); // Extends
ClockThread = New Thread (this, "clock"); // runnable
(Ii) Scheduling of thread
The thread scheduler selection high priority thread (enter the run state) executed by the priority of the thread. The priority thread is used to represent the range from 1 to 10, that is, thread.min_Priority to Thread.max_Priority. The default priority of a thread is 5, namely thread.norm_priority.
Example: void setPriority (int newpriority);
Thread control
Termination thread
STOP () to terminate the thread
Test thread state
Get whether the thread is active by the isalive () method in THREAD.
Pause and recovery of thread
1) SLEEP () method
2) Join ()
Mutual exclusion and synchronization of thread
In order to resolve the incompleteness of the operation, in the Java language, the concept of object mutual blaming is introduced to ensure the integrity of shared data operations. Each object corresponds to a tag that can be called "mutex", which is used to ensure that there is only one thread to access the object. Keyword synchronized contacts with the mutex lock.
example:
Public void push (char c) {
Synchronized (this) {// this represents the current object of Stack
DATA [IDX] = C;
IDX ;
}
}
Public char pop () {
Synchronized (this) {
IDX -;
Return Data [IDX];
}
}
Synchronized also modified methods and classes
note:
Wait, NOFITY, NOTIFYALL must be performed in the case where there is already a lock, so they can only appear in the range of the synchronized effect, that is, in the method or class that is modified with synchronized.
Thread group
Threads are individually created, but they can classify them into thread groups to facilitate debugging and monitoring. You can only associate it with a thread group while creating a thread. In programs that use a large number of threads, use thread group organization threads may be helpful.
Inter-thread communication
When threads need to wait a condition before continuing execution, only the synchronized keyword is not enough. Although the Synchronized keyword blocks concurrently updated an object, it does not implement the thread. The Object class provides three functions for this: Wait (), Notify () and NotifyAll ().
I / O operation
Two major categories: InputStream and OutputStream, Reader and Writer
I byte flow:
A series of classes derived from InputStream and OutputStream. This type of stream is based on byte (byte).
◇ InputStream, OutputStream
◇ FileInputStream, FileOutputStream
◇ PipedinputStream, Pipedputstream
◇ ByteaRrayinputStream, ByteArrayoutputstream
◇ FilterInputStream, FilterOutputStream
◇ DataInputStream, DataOutputstream
◇ BufferedInputStream, Bufferedoutputstream
II character stream:
A series of classes derived from Reader and Writer, such streams are characterized by characters represented by 16-bit Unicode code.
◇ Reader, Writer // Abstract base class
◇ InputStreamReader, OutputStreamwriter
◇ FileReader, FileWriter
◇ ChararrayReader, ChararrayWriter
◇ PipedReader, PiPedWriter
◇ FilterReader, FilterWriter
◇ BufferedReader, BufferedWriter
◇ StringReader, StringWriter
III object flow
◇ ObjectInputStream, ObjectOutputStream
IV other
◇ File processing:
File, randomaccessfile;
◇ interface
DataInput, DataOutput, ObjectInput, ObjectOutput;
The class file provides an attribute that describes a file object-independent manner.
Class FileInputStream and FileOutputStream are used to perform file I / O processing, and the methods they provide can open the files on the local host and perform read / write in order. Random access files allow random read / write to file content. In Java, class randomaccessfile provides a method of random access files.
The filter flow can be processed on the data while reading / writing data. It provides a synchronization mechanism that allows only one thread to access an I / O stream at a certain moment to prevent multiple threads while operating the I / O stream. The unexpected result is brought. Class FilterInputStream and FilterOutputStream are respectively the parent class for all filtration input streams and output streams, respectively.
Several common filters
◇ BufferedInputStream and BufferedoutputStream
Buffering stream is used to improve the efficiency of input / output processing.
◇ DataInputStream and DataOutputstream
Not only can read / write data streams, but also read / write the basic type of various Java languages.
◇ LINENUMBERINPUTSTREAM
In addition to providing support for input processing, LINENUMBERINPUTSTREAM can log the current line number.
◇ PushbackInputStream
A method provides a way to return the number you just read to the input stream to re-read it again.
◇ PrintStream
The function of printing is to send the internal structure of the Java language to the corresponding output stream in its character representation.
Character flow processing
Java provides a class that depends on the character stream represented by 16-bit Unicode code, which is a series of classes that are derived from Reader and Writer as base classes.
The IReader class is the parent class that handles all character streams.
The IIWRITER class is the parent class that handles all character stream output classes.
These two classes are abstract classes, just provide a series of interfaces for character stream processing, unable to generate these two classes, can only process the character stream by using sub-objects they derived. Such as InputStreamReader and OutputStreamWriter; BufferedReader and BufferedWriter.
Object serialization
The life of the object typically terminates with the termination of the program that generates the object. Sometimes, you may need to save the status of the object and restore the object when you need it. We use this object to record your own state to reproduce the ability to regenerate, called the persistence of the object. The object records yourself by writing a value that describes its state, the serialization of the object. Realize serialization needs to inherit the Serializable interface. In the Java.IO package, ObjectInputStream and ObjectOutputStream are provided to extend data stream functions to readable and write objects.
Serialized energy saved elements
You can only save the non-statistial member variables of the object, and no member method and static member variables can be saved, and serialization is only the value of the variable, and for any modifier of the variable, it cannot be saved.
TRANSIENT keyword
For some types of objects, its status is instantaneous, such objects are unable to save their status, such as a Thread object, or a fileInputstream object, for these fields, we must use the transient keyword
Custom serialization
The default serialization mechanism, object serialization first writes information about class data and class fields, and then writes its value in order to the raised arrangement of the name. If you want to clearly control the write order and writing types of these values, you must define your own way you read the data stream. That is to override the WriteObject () and ReadObject () methods in the definition of the class.
Note: You must remember to speak (or file) after using the performed (or file): in.close (); out.close (); f.close ();
Several common situations of flow processing (flow room):
I BufferedInputStream Bis = New BufferedInputStream (System.IN); SYSTEM.IN
BufferedoutputStream Bos = New BufferedOutputStream (New File ("FileName");
II InputStreamReader IN = New InputStreamReader (System.in);
OutputStreamwriter out = new outputStreamWriter (New
FileOutputStream ("filename.txt"));
III BUFFEREDReader in = New InputStreamReader (System.in));
BufferedWriter out = new bufferedwriter (New OutputStreamwriter
FileOutputStream ("filename.txt"));
PrintWriter out = new printwriter ("filename.txt");
Iv fileinputstream fin = new fileinputstream (filename); /
FileOutputStream Fos = New FileOutputStream (New File ("FileName"));
V DataInputStream DIN = New DataInputStream (New FileInputStream ("FileName.Dat")))))
DataInputStream DIN = New DataInputStream (NewBufferedInputStream (NewBufferedInputStream
FileInputStream ("filename.dat")))))))
VI ObjectInputStream S = New ObjectInputStream (New FileInputStream ("FileName.ser");
ObjectOutputStream S = New ObjectOutputStream (New
FileOutputStream ("filename.ser");
VII RandomaccessFile INOUT = New RandomaccessFile ("Filename.dat", "RW");
Basic network technology
principle:
In the TCP / IP protocol, the IP layer is mainly responsible for the location of the network host, the route of data transmission, and the IP address can uniquely determine a host on the Internet. The TCP layer provides an application-oriented reliable or non-reliable data transmission mechanism, which is the main object of network programming, which generally does not need to care about how the IP layer handles data. The currently popular network programming model is a client / server (C / S) structure. That is, the communication between the communication is waiting for the customer as a server to make a request and respond. The customer will apply to the server when the service is required. The server is generally running, listening to the network port as a daemon, and once a customer request will start a service process to respond to customers, while continuing to listen to the service port, making later customers to get timely service.
Network Basic Concept
IP address: Identify network addresses of network devices such as computers, composed of four 8-bit binary numbers, separated by decimal points.
Hostname: Help Name of the network address, grade the domain name. Port Number: The identity of different processes on the same machine when network communication.
Service Type (Service): Various services of the network.
Note: Typically there are always many processes on a host to require network resources for network communication. The importance of network communication is not the host, but should be the process running in the host. At this time, light has a host name or IP address to identify that many processes are obviously not enough. The port number is to take a means of providing more network resources on a host, which is also a mechanism provided by the TCP layer. Only a combination of host name or IP address and port number can only determine the object in the network communication: process.
Two types of transport protocols: TCP; UDP
TCP is an abbreviation of Tranfer Control Protocol, a protocol that guarantees reliable transmission. The TCP protocol is transmitted to obtain a sequential errorless data stream. The two Sockets of the sender and the receiver must establish a connection to communicate on the basis of the TCP protocol. When a socket is waiting to establish a connection, another Socket can request a connection. Once these two sockets are connected, they can perform two-way data transmission, both sides can transmit or receive operations.
UDP is the referusion of User DataGram Protocol. It is an unconnected protocol. Each datagram is a separate information, including a complete source address or destination address, which is passed on the network with any possible path to destination, Therefore, it is not possible to reach the destination, the time of arriving at the destination, and the correctness of the content cannot be guaranteed.
Note: Since there is a TCP protocol that guarantees reliable transmission, why should it be non-reliable transfer UDP protocol? There are two main reasons. First, reliable transmission is to pay the price, and the test of the correctness of the data will inevitably take up the computer's processing time and network bandwidth, so the efficiency of TCP transmission is not as high as UDP. Second, in many applications, there is no need to ensure strict transmission reliability, such as video conferencing systems, do not require the audio video data absolutely correct, as long as the coherence can be, it is clear that UDP will be more reasonable. .
Create a URL
The constructor of the class URL declares that the MalformedurLexception is discarded, so when you generate a URL object, we must process this exception, usually in the TRY-CATCH statement to capture. The format is as follows:
Try {
URL MyURL = New URL (...);
} catch (Malformedurlexception E) {
....
}
Read WWW network resources from the URL
When we get a URL object, you can read the specified WWW resource by it. At this time we will use the URL method OpenStream (), which is defined as:
InputStream OpenStream ();
Method OpenSteam () establishes a connection to the specified URL and returns an object of the InputStream class to read data from this connection.
EX: BufferedReader IN = New BufferedReader (NEW URL (...)). OpenStream ());
Connect to the URLConnetction WWW
Class URLConnection provides many ways to set up or get a connection parameters, and the most commonly used programming is getOrPutStream () and getourPutStream (), which is defined as:
InputSteram getInputSteram ();
OutputSteram getOutputStream (); We can communicate with the remote object by returning input / output stream. Look at the example below:
URL URL = New URL ("http://www.javasoft.com/cgi-bin/backwards");
// Create a URL object
UrlConnectin Con = URL.OpenConnection ();
// Get URLConnection object by URL object
DataInputStream DIS = New DataInputStream (con.getinputsteam ());
// Get the input stream by URLConnection, and construct a DataInputStream object
PRINTSTREAM PS = New Printsteam (con.getUpsteam ());
// Get the output stream by URLConnection, and construct the PrintStream object
String line = disp.readline (); // read from the server
ps.println ("Client ..."); / / Write the string "Client ..." to the server
Low-level Java network programming based on Socket (socket)
The two programs on the network implements data exchange through a two-way communication connection, and one end of this bidirectional link is called a socket. Socket is usually used to connect to the client and the server. Socket is a very popular programming interface of the TCP / IP protocol, and a socket is uniquely determined by an IP address and a port number.
Socket communication general process:
The general connection process of the CLIENT / Server programming is designed using Socket is: Server Listen (listening) Some ports have a connection request, the Client side issues a Connect (connection) request to the Server side, the Server is sent back to the client side back Accept (Accept) message. A connection is established. Server and Client ends can communicate with each other via Send, Write.
For a fully fully fully equipped socket, the following basic structure is included, and its work procedure contains the following four basic steps:
(1) Create a Socket;
(2) Open the input / exit connection to the socket;
(3) Read / write the Socket in accordance with certain protocols;
(4) Turn off the socket.
Note that when you select a port, you must be careful. Each port provides a specific service, only the correct port can be obtained. The port number of 0 ~ 1023 is the system.
Client's socket
Try {
Socket Socket = New Socket ("127.0.0.1", 8080);
} catch (ioexception e) {
System.out.println ("Error:" E);
}
ServerSocket
Serversocket Server = NULL;
Try {
Server = new serversocket (8080);
} catch (ioexception e) {
System.out.println ("Can Not Listener TO: E);
}
Socket Socket = NULL;
Try {
// accept () is a blocking method. Once there is a customer request, it will return a socket object to interact with the customer.
Socket = server.accept ();} catch (ooException e) {
System.out.println ("Error:" E);
}
Open Input / Export Socket provides method getInputStream () and getoutStream () to get the corresponding input / output stream for read / write operation, which returns the inputStream and OutputSteam class objects. Objects. To facilitate reading / write data, we can create filter flows on the return input / output stream object, such as DataInputStream, DataOutputStream or PrintStream class object, and for text-flow objects, INPUTSTREAMREADER and OUTPUTSTREAMWRITER, PRINTWIRTER and other processing can be used.
Close Socket
When each socket exists, you will take up a certain resource. When the Socket object is used, it is closed. Turn off the socket to call the CLOSE () method of the socket. All input / output streams associated with socket should be turned off before shutting down sockets to release all resources. Moreover, pay attention to the sequence of closing, all input / output related to socket, then turn off, then close the Socket.
Data report (DATAGRAM)
The BRAGRAM will not guarantee reliable delivery, and the link-oriented TCP is better than the phone, and the two sides can affirm the other party to accept information.
DataGram communication representation: DataGramsocket; DataGrampacket
principle:
Both class DataGramsocket and DataGramsocket and DataGramPacket are used to support datagram, and DataGramsocket is used to establish a communication connection between programs, and DataGraMpacket is used to represent a datagram. When writing a Client / Server program in a datagram, a DataGramsocket object is first established in the client or the service, first to receive or send datagrams, then use the DataGrampacket class object as a carrier for transferring data. Before receiving data, the first method of the above should generate a DataGrampacket object to give the buffer and length of the received data. Then call the DataGramsocket method receive () Waiting for the date of the datagram, Receive () will wait until a datagram is received.
DataGrampacket Packet = New DataGrampacket (buf, 256);
Socket.Receive (Packet);
Before sending data, you must be a new DataGrampacket object. At this time, you should use the second constructor above, while give a complete destination address, including an IP address. And port numbers. The transmission data is implemented by the method Send () of the DataGramsocket, and Send () is recorded according to the destination address of the datagram to deliver the datagram.
DataGrampacket Packet = New DataGrampacket (BUF, Length, Address, Port)
Socket.send (packet);