(eight) multithreading mechanism of Java

Source: Internet
Author: User
Tags thread class

One, program, process, and thread:
1, the program is a static code, it is the application of the implementation of the blueprint.

2, the process is a process of dynamic execution of the program, which corresponds to the loading from code, execution to completion of a complete process, the process itself from the generation, development to extinction process.

3, the thread is smaller than the process of the unit, a process execution can produce multiple threads, each thread has its own production, existence and extinction process, but also a dynamic concept. Each process has a dedicated memory area, and the threads can share the same area of memory (including code and data) and use these shared units for data exchange, real-time communication, and necessary synchronization operations.

Each Java program has a default main thread. Java programs are always executed from the main method of the primary class. When the JVM loads the code and discovers the Main method, it starts a thread called the "main thread", which is responsible for executing the main method. The thread that is created in the main method is another thread. a thread is a different execution path within a program.

If no other thread is created in the main method, the JVM ends the Java application when the main method returns. However, if other threads are created in the main method, then the JVM will switch between the main thread and the other threads, ensuring that each thread has the opportunity to use the CPU resources, the Main method returns (the main thread ends) the JVM will not end, and wait until all the threads of the program end to end the Java program ( Another scenario is that the exit method for the runtime class is called in the program, and the security Manager allows the exit operation to occur. The JVM will also end the program).
4. The difference between threads and processes:

4.1 Each process has a separate code and data space (process context), and there is a significant overhead involved in switching between processes.

4.2 Threads can be thought of as lightweight processes, sharing code and data spaces with a class of threads, each with a separate run stack and program counter, and a small overhead for thread switching.

4.3 Multi-process: Ability to run multiple tasks (programs) in the operating system

4.4 Multi-Threading: Multiple sequential streams executing in the same application

5, the basic concept of threading:

Java threads are implemented through the Java.lang.Thread class.

When the VM starts, it has a thread defined by the main method (public static void Main () {}).

You can create a new thread by creating an instance of the thread.

Each thread completes its operation by means of the method run () that corresponds to a particular thread object, and the method run () is called the thread body.

Start a thread by calling the start () method of the thread class, at which point the thread enters the operational state. Notifies the CPU, there is another execution path, when can give the opportunity to run, at this time the thread enters the operational state.

Second, the State and life cycle of the thread:
Java uses the object of the Java.lang.Thread class and its subclasses to represent the thread, and the new thread typically undergoes the following four states in its full life cycle: (New, operational, run, (Interrupt/suspend/block), extinct)
1. NEW:
When a thread class or its subclass object is declared and created, the newborn thread object is in the new state (at this point it already has memory space and other resources).

2. Operational status: When the thread is eligible to run, but the scheduler has not selected it as the state in which the thread is running. When the start () method is called, the thread first enters the operational state. After the thread has run or has returned from blocking, waiting, or sleeping, it returns to the operational state.


2. Operation:

The only way a thread can enter a running state is when the thread scheduler selects a thread from a running pool as the current thread's state.

A thread has been created to run a condition, and once it comes to the CPU resource, that is, when the JVM switches the CPU usage to that thread, the thread can start its own lifecycle independently of the main thread that created it.
After a thread is created with only a memory resource, and there is no such thread in the JVM-managed thread, the thread must call the Start () Method (inherited from the parent class) to notify the JVM, so that the JVM knows that a new thread is queued for switchover.

When the JVM switches the CPU usage to the thread, if the thread is created by a subclass of thread, the run () method in the class executes immediately (the specific mission of the thread is specified in the run () method). The run () method in the thread class has no specific content, and the program overrides the parent class by overriding the run () method in the subclass of the thread class. (Note: Do not call the Start method again before the thread ends the run () method, or the illegalthreadstateexception exception will occur)

3. Hang up:
There are four reasons why a thread hangs:
(1), the JVM switches the CPU resources from the current thread to other threads, making this thread give up the use of the CPU and is in a suspended state.
(2), while the thread is using CPU resources, the sleep (int millsecond) method is executed to put the current thread into hibernation. The Sleep (int Millsecond) method is a class method in the thread class that, when executed by the thread, immediately yields the CPU usage and goes into a pending state. After the number of milliseconds specified by the parameter Millsecond, the thread re-enters the thread queue to wait for CPU resources and then continues to run from the middle.
(3), while the thread is using CPU resources, the Wait () method is executed to allow the current thread to enter a wait state. A thread waiting for a state does not actively enter the thread queue to wait for CPU resources, and must be notified by other threads to call the Notify () method to allow the thread to wait for CPU resources from a new entry into the thread queue to continue running from the point of interruption.
(4), when a thread uses CPU resources, it performs an operation that goes into a blocking state, such as performing a read/write operation that causes blocking. The thread cannot enter the thread queue when it enters the blocking state, and only when the cause of the blocking is eliminated, the thread can go into the thread queue and wait for the CPU resource to continue running from the point of interruption.


4. Death:
The state of death is that the thread releases the entity, freeing the memory allocated to the thread object. If you call the start () method on a dead thread, the java.lang.IllegalThreadStateException exception is thrown.

There are two causes of thread death:
(1), the normal running thread completes all its work, that is, executing all the statements in the run () method, ending the Run () method.
(2), the thread is pre-mandatory termination, that is, forcing the run () method to end.

5. Thread state transition diagram

Third, thread scheduling and priority:
The thread scheduler of the JVM is responsible for managing threads, and the scheduler divides the priority of threads into 10 levels, represented by class constants in the thread class, respectively. Each Java thread has a priority between constant 1-10. The thread class has a priority constant of three:
static int min_priority//1
static int norm_priority//5
static int max_priority//10
If not explicitly set, the default thread priority is constant 5, which is thread.norm_priority.

The thread priority can be adjusted with the setpriority (int grade) method, and SetPriority produces a illegalargumenexception exception if the parameter grade is not in the 1-10 range. Returns the thread priority using the GetPriority () method. (Note: Some operating systems can only recognize 3 levels: 1, 5, 10)

The task of the Java scheduler is to enable threads with high priority to always run, and once the time slices are idle, the threads with the same priority will use the time slices in a rotational fashion. A low-level thread has the opportunity to gain CPU resources only when a high-ranking thread dies (unless the CPU resources are made out with sleep (int millsecond) or the Wait () method).

In practical programming, the use of thread precedence is not advocated to ensure proper execution of the algorithm. To write correct, cross-platform multithreaded code, it is important to assume that threads can be deprived of the use of CPU resources at all times.

Four, there are two ways to implement multithreading in Java:
1. Inherit the thread class, overriding the Run () method: The advantage of creating a thread with the thread subclass is that you can add a new member variable or method to the subclass so that the thread has some kind of property or function. However, Java does not support multiple inheritance, and subclasses of the thread class can no longer extend other classes.
2, implement Runnable interface: Create thread object directly with thread class, use constructor thread (Runnable target) (parameter target is a Runnable interface), When you create a thread object, you must pass an instance of the implementation runnable interface class to the constructor method parameter, which is called the target object of the created thread. When a thread calls the start () method, the target object automatically calls the Run () method (interface callback) in the interface once it has its turn to use CPU resources.

The same memory units (including code and data) can be shared between threads, and these shared units are used for data exchange, real-time communication, and necessary synchronization operations. For threads created with the thread (Runnable target) that use the same target object, you can share the target object's member variables and methods.
In addition, creating a target object class can be a subclass of a particular class if necessary, so using the Runnable interface is more flexible than a subclass that uses thread.
(Note: A thread with the same target object, the local variables in the run () method are independent of each other and do not interfere with each other)

Other threads are started in the thread, and when the threads call the start () method to start, so that it enters the ready queue from the new state, once the CPU resources are removed from the main thread that created it, start its own life cycle.

V. Common Methods of Threading:

Thread Control Basic methods:


Start (): The thread calls the method to start the thread, from the new state into the ready queue, once the CPU resources can be separated from the creation of its thread, independent start their own life cycle.

Run (): the Run () method of the thread class is the same as the run () method in the Runnable interface and is used to define the operations that are performed after the thread object is dispatched, which are methods that the system automatically calls and the user must not refer to. When the run () method is executed, the thread becomes dead, that is, the thread frees the memory allocated to it (the dead state thread can no longer invoke the start () method). You cannot have the thread call the start () method again until it has finished the run () method, or the illegalthreadstateexception exception will occur.

Sleep (int millsecond): Sometimes a high-priority thread needs a low-priority thread to do some work to match it, so that the priority thread is given the CPU resources, the lower priority thread has the opportunity to run, and the sleep (int millsecond) method can be used. When the thread is interrupted during hibernation, the JVM throws a Interruptedexception exception. Therefore, you must call the Sleep method in the Try-catch statement block.

IsAlive (): When a thread calls the start () method and occupies a CPU resource, the run () method of the thread starts running, and calls IsAlive () before the run () method ends () returns True when the thread is in a new state or a dead state called isAlive () returns FALSE.
Note: An already running thread does not assign an entity to it when it is not in the dead state, and since the thread can only refer to the last assigned entity, the previous entity becomes "garbage" and cannot be collected by the garbage collection mechanism.

CurrentThread (): Is a class method of the thread class that can be called with the class name to return the thread that is currently using the CPU resource.

Interrupt (): When a thread calls the sleep () method in hibernation, a thread that occupies a CPU resource can let the dormant thread call the interrupt () method to "wake up" itself, That causes the thread to illegalthreadstateexception the exception, thus ending hibernation and waiting for CPU resources to be queued again.

GUI Thread: The JVM will automatically start more threads when it runs an application containing graphical interfaces, with two important threads: Awt-eventqueue and Awt-windows. The Awt-eventqueue thread is responsible for handling GUI events, and the awt-windows thread is responsible for drawing the form or component to the desktop.

Thread synchronization: (Modify a method with synchronized, which modifies variables that need to be synchronized; or modifies basic variables with volatile)
When two or more threads access a variable at the same time, and a thread needs to modify the variable, the problem should be handled, or chaos may occur.

To handle thread synchronization, you can modify the data by using the keyword synchronized modifier. One method uses the synchronized adornment, and when a thread a uses this method, other threads must wait until thread a finishes using the method when they want to use it. The so-called synchronization is that multiple threads need to use a synchronized decorated method.

Volatile is simpler than synchronization and is only appropriate for controlling access to individual instances of basic variables (integers, boolean variables, and so on). The volatile keyword in Java is the same as in C + +, where volatile-modified variables are not optimized for read and write operations (taking the values in the cache to improve IO speed), but instead directly manipulate main memory. This means that all threads see the same volatile variable value at any time.

Vi. Use the Wait (), notify (), and Notifyall () methods in the synchronization method:
You can use the Wait () method in a synchronous method when a variable is used in the synchronization method used by a thread, and the variable needs to be modified by another thread to meet the needs of this thread. Interrupts the execution of the method, causes the thread to wait, temporarily yields the CPU resources, and allows other threads to use the synchronization method. If the other thread does not need to wait while using this synchronization method, it should use the Notifyall () method to notify all the waiting threads that are waiting by using this synchronization method. Threads that have been interrupted will continue to execute from the break and follow the principle of "first break first". If you use the Notify () method, then just notify the waiting thread that one of the end waits.

Timer Thread Timer: (timer also has a lot of advanced operations, see the JDK in detail, here is an overview)
The Java.swing.Timer class is used periodically to perform certain operations. There are two common constructors
public timer (int delay, ActionListener listener): Parameter listener is the monitor of the timer, the event that the timer is ringing is the ActionEvent type event, when the ringing event occurs, The monitor monitors this event and recalls the actionperformed (ActionEvent e) method in the ActionListener interface.

public timer (int delay): Using this construction method, the timer calls the addActionListener (ActionListener Listener) method to get the monitor.

If you want the timer to vibrate only once, you can have the timer call the SetRepeats (Boolean B) method, and parameter B takes false.
The timer can also call the setinitialdelay (int delay) method to set the time delay for the first ringing, if not set the first ringing default delay to the parameter delay in the constructor.
You can also call Getdelay () and setdelay (int delay) to get and set the delay.
After the timer is created, call Start () to Start, call Stop () stop, that is, suspend, call restart () to restart the timer, that is, the recovery thread.

Thread Federation:
While a thread A is occupying CPU resources, it is possible for other threads to call the join () method and this thread union, such as:
B.join ();
At this time it is called a during the run Union B. At this point a thread is executed immediately, waiting until its federated thread B finishes executing, and a thread is re-queued for CPU resources. However, B.join () does not produce any effect if a ready-to-federate thread B has ended.


Daemon Thread:
The thread defaults to a non-daemon thread, and a thread called the Setdaemon (Boolean on) method can set itself as a daemon (Daemon) thread, such as:
Thread.setdaemon (TRUE);
A thread must set itself to be a daemon thread before it runs itself. A daemon is a daemon thread that ends up running when all user threads in the program have finished running, even if the daemon's run () method has a statement that needs to be executed. So the daemon is used to do something that is not very strict and does not have any bad consequences when the thread ends at any time.

This article is mainly from the CSDN blog, but summarizes some new things. In order to respect the original, reproduced please indicate the source: http://blog.csdn.net/lj70024/archive/2010/04/06/5455790.aspx

(eight) multithreading mechanism of 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.