Note (Java)

Source: Internet
Author: User
Tags thread class throw exception throwable

Inner class Advantages: 1. Members of external classes can be accessed directly, including private.
Members of an external class can be accessed directly because the inner class holds a reference to an external class, in the form of an external class name. This
2. External classes to access internal classes must establish an inner class object

Access format: When an inner class is defined on the member location of an external class and is not private, it can be in an external other class. You can create an inner class object directly.
Format: outer class name. Internal class Name Variable name = External Class object. Inner class object;
Outer.Inner in =new Outer (). Inner ();
Private Inner class
Static: The inner class has the static property, and when the inner class is modified by static, it can only directly access the static plotting element in the outer class, and there is an access limitation.
New Outer.Inner (). Funcation ();
Outer.Inner (). Funcation ();
Note: When a static member is defined in an inner class, the inner class must be static.
When an external static method accesses an inner class, the inner class must also be static.
When describing things, there are 15 of things inside, which are described by internal classes. Because internal things are using the content of external things.
When the inner class is defined locally,
1. Can not be modified by member modifiers
2. Members in external classes can be accessed directly because they also hold references in external classes. However, it is not possible to access the variables of his local area. Only the final decorated local variables can be accessed.
Anonymous inner class
1. The anonymous inner class is actually the intermittent format of the inner class.
2. Prerequisites for defining anonymous internal classes:
The inner class must inherit a class or implement an interface.
3. The format of the anonymous inner class: New parent class or interface () {Defines the contents of a subclass}
4. In fact, the anonymous inner class is a subclass of your name and the object is a bit fatter. An object that is willing to be understood as content.
New Absdemo ()
{
void Show () {
System.out.print ("x=" +x);
}
}.show ();
Polymorphic subclasses can only call parent class methods
5. It is best not to have more than 3 methods defined in an anonymous inner class.

Members in Java that are decorated statically are called static members or class members. It is owned by the entire class, not by an object, which is shared by all objects of the class. Static members can be accessed directly by using the class name or by using the object name.

Abnormal

Exception: is the program at run time in early summer abnormal situation.
Exception Origin: The problem is also a specific thing in life, can also be described in the form of Java classes. and encapsulated into objects.
In fact, Java is a description of the abnormal situation after the object.
The problem is divided into two kinds: one is a serious problem, a non-serious one.
For serious, Java is described by the error class.
For error, it is generally not written for custom code to handle it.

For non-critical, Java is described by the exception class.
For exception, you can use a targeted processing method for processing.

Both error and exception have some common content.
For example: abnormal information, causes of the cause and so on.

Throwable
|--error
|--excaption

2. Handling of exceptions

Java provides a unique statement to handle
Try
{
Code that needs to be detected;
}
catch (Exception class variable)
{
Code to handle exception (processing mode)
}
Finally
{
Statements that are bound to be executed;
}

3.. getMessage ()//Exception Name: Exception information
. toString ()//Exception Name: Exception information, where a wipe is very capable of appearing
. Printstacktrace ()//exception name, exception information, where the exception occurred.
In fact, the JVM descendants of the exception handling mechanism is called printstacktrace method.
Prints trace information for the stack of exceptions.

Throws exception//Exception declaration
Handling of multiple exceptions
1. When declaring an exception, it is recommended to declare a more specific exception. This can be handled more concretely.
2. The other party declares several exceptions, which correspond to several catch blocks. Do not define an extra catch block
If an inheritance relationship occurs in multiple catch blocks, the parent exception catch block is placed at the bottom.

It is recommended that you define the specific handling in catch when you are doing catch processing. Don't simply define a e.printstacktrace (), or simply write an output statement.

Custom exceptions
Used to customize the encapsulation of unique issues.
You must customize class inheritance Excaption
Inheritance excaption Reason:
One of the features of a system is that the exception class and the abnormal sound are thrown.
They all have throwable, which is the unique feature of the system.
Only classes and objects in this system can be throws and throw operations.
Throws exception{
Throw Exception
}
Thorws used on a function
Throw is used within a function
Throws followed by the exception class, you can follow multiple. separated by commas.
The throw is followed by an exception object.
There is a special subclass exception RuntimeException run-time exception in exception.
If the exception is thrown within a function, the function can be passed without declaration and compilation.
If an exception is declared on a function, the caller can do so without processing, and the compiler can pass

It is not necessary to declare the function because it does not need to be handled by the caller.
When the exception occurs, you want the program to stop. Because at run time, there is a failure to continue operation of ING mad, want to stop the program, the code to be corrected.

Custom exception: If the exception occurs, you cannot continue the operation, let the custom exception inherit RuntimeException

There are two types of exceptions:
1. Compiling the detected exception
2. Exceptions that are not detected at compile time (runtime exceptions). RuntimeException and its subclasses)

This: Represents the Thunder object, which object calls this function, this represents which object.

Final
1. Modifier classes, variables (member variables, static variables, local variables), functions.
2. A decorated class cannot be inherited.
3. The ethics function can not be overwritten
4. The modified variable is a constant and can only be assigned once.
5. Inner classes can only access local final variables


Polymorphic member variables do not overwrite method overrides
Throw is present separately, do not define the statement below, because do not
Multiple catch, the parent class catch is placed below
Static Call static
Return still executes final statement in Catch block

Packages (Package)
1. Classification management of class files
2. Provide multi-level namespaces for classes
3. Write in the first line of the program file
4. The entire class name is the package name. Class name.
5. Packages are also a form of encapsulation.

Jar Package
Java-Compressed Packages
Easy to carry items
Easy to use, just set the jar path in Classpath
Data can be driven, SSH framework, etc. are in the jar package embodied

Process: is an executing program
Each process execution has an execution order. The order is an execution path, or a control unit.
Thread: Is the total process of a separate control unit.
Threads are executed in the controller process.

There is at least one thread in a process.

A Java VM will start with a process Java.exe

At least one thread in the process is responsible for the execution of the Java program.
And the code that this thread runs on is in the Main method
This thread is called the primary thread.

Extension: In fact, more details indicate that the JVM,JVM boot does not know a thread, there is a garbage collection mechanism responsible for the thread.


1. How do I customize a thread in the code that defines it?

Inherit the thread class by first way of sliding cover
Steps:
1. Define class inheritance thread.
2. The Run method in the replication thread class
Purpose: Speak custom code stored in the Run method. Let the thread run.
3. Call the thread's Start method
The method has two functions, starting the thread and calling the Run method.

found that the results of the run are different every time.
Because multiple threads are getting the CPU's execution rights. The CPU executes to whom, who runs it.
Clear I point, in a moment, can only have a training in operation. (except multicore)
The CPU is doing a quick switchover to achieve the effect that appears to be running simultaneously.
We can figure it out. Multi-threaded running behavior in each other to rob the CPU execution rights.

This is one of the features of multithreading: Randomness, who Rob who execution, as to how long the CPU to decide.

Why overwrite the Run method?

The thread class is used to describe threads.
The class defines a feature that stores the code that the thread will run, which is the Run method.

This means that the run method in the tread class is used to store code that first plans the concept to run.


Execution status: Created run blocking freeze temporary extinction

The original thread has its own default name (. GetName ())
tread-number This number starts from 0
Tread.currenttread () ==this the previous invocation method is generic

Static thread Crrentthread (): Gets the current thread object.
GetName (): Gets the thread name

Set thread Name: SetName or constructor.

Second way to create a thread: implementing the Runnable Interface

Steps:
1. Define class implementation Runnable interface
2. Overwrite the Run method in the Runnable interface
The code that the thread wants to run is stored in the Run method.

3. Thread objects are established through the thread class.
4. The subclass object that speaks the Runnable interface is passed as an actual parameter to the constructor of the thread class.
Why pass the subclass object of the Runnable interface to the constructor of thread.
Because the custom run method belongs to the object is the subclass object of the Runnable interface.
So to get the thread to specify the object's Run method, the snort explicitly specifies the object to which the Run method belongs.

5. Call the thread class Start method to open the thread and invoke the Run method of the Runnable interface subclass.


What is the difference between an implementation and a way of inheriting?

Implementation benefits: Avoids the limitations of single inheritance.
It is recommended to use implementations when defining threads.

There are two different ways to differentiate:
Inherit thread: The threading code is stored inside the thread subclass Run method.
To implement runnable, the thread code has the Run method of the subclass of the interface.

The cause of the problem:
When multiple statements are working on the same thread to share data, one Xiacheng only executes a portion of the multiple statements, and it has not finished executing.
Workaround:
A statement that shares data on multiple operations can only have one thread read execution. During execution, other threads are not allowed to participate in execution.

Java provides a multi-threaded security issue

is to synchronize the code block

Synchronized (object)
{
Code that needs to be synchronized
}

The object is like a lock, and the thread holding the lock can execute in the synchronization.
A thread without a lock acquires the CPU's execution immediately, and cannot get in because the lock is not acquired.

Prerequisites for synchronization:
1, there must be two or more than two threads.
2, the same lock must be used by multiple threads.

You must ensure that only one of the threads in the synchronization is running

Benefits: Solves the problem of multithreading security.

Disadvantage: Multiple threads need to determine the lock, more waste of resources.

How to find a problem:
1, make clear what code is multithreaded to run the code.
2, clear sharing of data
3, clear which statements in multithreaded run code are operations that share data.


Synchronization function: With synchronized decoration can

Which lock does the synchronization function use?
The function needs to be called by the object, so the function has a reference to the owning object. That's it.
So the lock used by the sync function is this

If the synchronization function is statically decorated, what is the lock used?

Through validation, the discovery is not in this, because it cannot be defined in the can table method.

When static into memory, there is no Thunder object in memory, but there must be a corresponding bytecode file object for that class.
Class name. Class The type of the object is class

A static synchronization method that uses a lock that is the bytecode file object of the class in which the method resides. Class name.


Lazy Type: Lazy loading

Lazy Type:

Class single
{
private static single s=null;
Private single () {}

public static single getinstance () {
if (s==null) {
Synchronized (Single.class) {
if (s==null) {
S=new single ();
}

}

}
return s;
}
}


Dead lock
Synchronization is nested in sync, while locks are different

Note (Java)

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.