An in-depth discussion of Java threads

Source: Internet
Author: User
In general, we call the program that is executing on the computer called the process, not the
Called program. The so-called "thread" is a single sequential control flow in the process.
Emerging operating systems, such as Mac,windows Nt,windows 95, mostly use the concept of multithreading, the line
Process as a basic execution unit. Threads are also one of the most important components of Java.

Even the simplest applets are done by multiple threads. In Java, any applet's
The paint () and update () methods are both the AWT (Abstract Window Toolkit) Drawing and the event-handling line
--init (), Start (), Stop (), and Destory () are the main milestone methods for the applet.
-Called by an application that executes the applet.

The concept of single-threaded is nothing new, it's really interesting to use multiple lines at the same time in a program
To accomplish different tasks. In some places, lightweight processes (Lightweig HT process) are used to replace threads
, the similarity between threads and real processes is that they are all in a single sequential control flow. However the thread is considered to be light weight is
Because it runs within the context of the entire program, it can use the resources and program Environment common to the entire program.

As a single sequential control flow, the running of the program inside must have some resources as necessary overhead
。 For example, there must be an execution stack and a program counter. Code that executes within a thread is only in its context
, so some places use "execution context" instead of "thread".

2. Threading Properties

In order to use threads correctly and efficiently, you must understand all aspects of the thread and understand the Java real-time system.
You must know how to provide the thread body, the thread's lifecycle, how real-time systems dispatch threads, thread groups,
What is Phantom thread (Demo nthread).

(1) Thread body
All operations occur in the thread body, in the Java centerline Cheng is the run () side that inherits from the thread class
method, or the run () method in the class that implements the Runnable interface. When the thread is generated and initialized, the real-time system is tuned
With its run () method. The code within the run () method implements the behavior of the resulting thread, which is the main part of the thread
Part

(2) Thread state
The figure indicates the state of the thread at any point in its life cycle and causes the state to change
The method of change. This diagram is not a complete finite state diagram, but it basically sums up the more interesting and universal
's aspect. The following discussion is about the thread lifecycle.


New Thread State
Produces a thread object and generates a new one. When a thread is in a "new thread" state, it is simply
An empty thread object that is not yet allocated to system resources. Therefore, it can only be started or terminated. Any other exercise
Do all throw an exception.
Operational state (Runnable)
The start () method generates the necessary resources to run the thread, dispatches the thread to execute, and invokes the thread's run
() method. At this point the thread is in a running state. This state is not called a running state because the thread at this time is not
Always occupy the processor. Especially for PCs with only one processor, there can only be one at any time
A processor that is in a running state of a thread. Java through scheduling to achieve multithreading of the sharing of processors.

Non-running state (not Runnable)
When the following event occurs, the thread enters the runtime state.
The ①suspend () method is invoked;
The ②sleep () method is invoked;
The ③ thread waits for the condition variable by using wait ();
The ④ thread is in I/O wait.
Death State (Dead)
When the Run () method returns, or another thread calls the Stop () method, the thread enters the dead state. Usually APPL
ET uses its stop () method to terminate all threads it produces.

(3) Thread priority
Although we say that threads are running concurrently. But that is often not the case. As discussed earlier, when
When there is only one CPU in the system, multithreading is called dispatch in a single CPU in some order (schedu
Ling). Java uses a simple, fixed scheduling method, namely fixed priority scheduling. This algorithm is
Scheduling is implemented according to the relative priority of a running thread. When a thread is generated, it inherits the original thread's
Priority level. The priority can be modified as needed. At any one time, if there are multiple threads waiting to run,
The system chooses the highest-priority running thread to run. Only when it stops, automatically gives up, or because some kind of
The reason for this is that a non-running low priority thread can run. If two threads have the same priority, it
They will be run alternately.
Java real-time system thread scheduling algorithm is still mandatory, at any moment, if one is more than the other line
The state of a thread with a high priority is changed to run, and the real-time system will select that thread to run.

(4) Phantom thread
Any Java thread can be a phantom thread. It is used as an object running in the same process
and the service provider for the thread. For example, the HotJava browser has a ghost called a "background picture reader"
Thread, which reads pictures from the file system or network for objects and threads that require pictures.
The Phantom thread is a typical stand-alone thread in the application. It provides for other objects and threads in the same application
Service. The Phantom Thread's Run () method is typically an infinite loop that waits for a service request.

(5) Thread Group
Each Java thread is a member of a thread group. The thread group provides a mechanism to allow multiple thread sets
Within an object, and can operate on them as a whole. For example, you can use a method call to start or suspend
All threads within the group. Java thread groups are implemented by the Threadgroup class.
When a thread is generated, you can specify a thread group or put it in a default thread group by the real-time system.
A thread can belong to only one thread group, and cannot change the thread group it belongs to when the thread is produced.

3. Multi-thread routines

This is not much to say about the benefits of multithreading. But it has also brought some new problems. Just
It is not too difficult to overcome these problems when designing programs with special care.

(1) Sync thread
Many threads must consider sharing data or coordinating execution state with other threads in execution. It's
Synchronization mechanism is required. In Java, each object has a lock corresponding to it. But Java does not provide a separate LO
CK and unlock operations. It is implemented implicitly by the high level structure to ensure the corresponding operation. (However, we note
Java Virtual machines provide separate Monito renter and monitorexit directives to implement lock and Unlo
CK operation. )
The synchronized statement evaluates an object reference, attempts to complete the lock operation on the object, and completes the
Stop processing before the lock operation. When the lock operation completes the synchronized statement body is executed. When the statement body executes
Complete (whether normal or abnormal), the unlock operation completes automatically. As an object-oriented language, synchronized
Often used with methods. A better approach is if a variable is assigned by a thread and the other line
Process reference or assignment, then all access to the variable must be in a synchromized statement or synch
Within the Ronized method.
Let's assume a situation where thread 1 and thread 2 both access a data area and require that the thread 1 visit
Ask before thread 2, then only use synchronized can not solve the problem. This is in UNIX or Windows
NT can be implemented in Simaphore. And Java does not provide. Provided in Java are Wait () and Noti
FY () mechanism. Use the following:
Synchronized method-1 (...) {Call by thread 1.
∥access data area;
Available=true;
Notify ()
}
Synchronized method-2 (...) {∥call by thread 2.
while (!available)
try{
Wait (), ∥wait for Notify ().
}catch (interrupted Exception e) {
}
∥access Data area
}
Where available is a class member variable, the initial value is false.
If available is checked for false in Method-2, then call Wait (). The function of Wait () is to make the line
Process 2 into the non-running state, and unlock. In this case, method-1 can be invoked by thread 1. When performing
Notify () after. Thread 2 is transformed from a non-running state to a running state. When the method-1 call returns. Thread 2
The object can be locked again and the instruction after wait () is returned after the lock succeeds. This mechanism can also be applied to
Other more complex situations.

(2) Deadlock
If there are several concurrent threads in the program that compete for resources, it is important to ensure that the balance is balanced. System equilibrium
means that each thread has full access to a limited resource during execution. There's no starvation or deadlock in the system.
Thread. Java does not provide a mechanism for detecting deadlocks. For most Java programmers, preventing deadlocks is
A better choice. The simplest way to prevent deadlocks is to introduce serial numbers to competing resources, if a line
Process requires several resources, it must first get the small number of resources, and then request a large number of resources.

4. Summary

Threads are an important part of Java, and multithreading is a feature of Java. Although the synchronous mutex of Java is not
If some systems are so rich, they can also be satisfied with their proper use.

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.