Java Thread Multithreading Comprehensive parsing _java

Source: Internet
Author: User
Tags thread class

Multithreading is a very important Java knowledge point, in this small series for everyone to summarize Java thread Multithreading, very useful, I hope you can master Oh.

I. Thread life cycle and five basic states

For the life cycle of the Java thread, first take a look at the more classic diagram below:

The above diagram basically contains the important knowledge points of multithreading in Java. Master the above diagram of the various points of knowledge, the Java multithreading is basically mastered. Mainly include:

Java threads have five basic states

New State (new): When the thread object is created, it enters a new state, such as: thread t = new mythread ();

Ready state (Runnable): When the call Thread object's Start () method (T.start ();), the thread enters the ready state. A thread in the ready state simply indicates that the thread is ready to wait for CPU scheduling to execute, not that the T.start () is executed immediately;

Run state (Running): When the CPU begins to dispatch a thread that is in a ready state, the thread can actually execute, that is, into the running state. Note: The ready state is the only entry into the running state, that is, the thread must first be in the ready state in order to enter the running state.

Blocking state (Blocked): A thread in the running state temporarily abandons the right to use the CPU for some reason, stops execution, enters a blocking state until it enters the ready state, and has the opportunity to be called again by the CPU to enter the running state.

Depending on the cause of the blockage, the blocking state can be divided into three different kinds:

1. Wait for blocking: the thread in the running state executes the wait () method, which causes the thread to enter the waiting block state;

2. Synchronous blocking-the thread fails to acquire the synchronized synchronization lock (because the lock is occupied by another thread) and it enters the synchronized blocking state;

3. Other obstructions-the thread enters the blocking state by calling the thread's sleep () or join () or by making an I/O request. When the sleep () state times out, join () waits for the thread to terminate or timeout, or the I/O process completes, the thread is back in ready state.

Death status (Dead): The thread finishes or exits the run () method because of an exception, which ends the lifecycle.

Two. Java multi-threading creation and startup

The creation of Java threads is common in three basic forms

1. Inherit the thread class and override the run () method of the class.

Class Mythread extends Thread {
private int i =;
@Override public
Void Run () {for
(i =; I < i++) {
System.out.println thread.currentthread (). GetName () + "" + i);
}
} 
public class ThreadTest {public
static void Main (string[] args) {for
(int i =; I < i++) {
System.ou T.println (Thread.CurrentThread (). GetName () + "" + i);
if (i = =) {thread
mythread = new Mythread ();//Create a new thread mythread this thread into the new state thread
mythread = new Mythread (); Create a new thread mythread this thread into the new state
Mythread.start ();//Call the Start () method to make the thread enter the ready state
Mythread.start ();//Call Start () Method enables the thread to enter the ready state
}}

As shown above, inherit the thread class and define a new thread class Mythread by overriding the run () method, where the method body of the run () method represents the task that the thread needs to complete, called the thread execution body. When this thread class object is created, a new thread is created and entered into the thread-new state. By invoking the start () method of the Thread object reference, the thread enters the ready state, and the thread does not necessarily execute immediately, depending on the timing of the CPU scheduling.

2. Implement the Runnable interface and override the run () method of the interface, which is also the thread executor, creates an instance of the Runnable implementation class, and creates the thread object with this instance as target for the thread class. This thread object is the real thread object.

Class Myrunnable implements Runnable {
private int i =;
@Override public
Void Run () {for
(i =; I < i++) {
System.out.println thread.currentthread (). GetName () + "" + i);
}
} 
public class ThreadTest {public
static void Main (string[] args) {for
(int i =; I < i++) {
System.ou T.println (Thread.CurrentThread (). GetName () + "" + i);
if (i = =) {
Runnable myrunnable = new myrunnable ();//Create a Runnable implementation class object
thread thread = new Thread (myrunnable ); Create a new thread threading thread
= myrunnable (myrunnable) as thread target;
Thread.Start (); Invoke the Start () method to allow the thread to enter the ready state
Thread.Start ();}}

Believe that the above two ways to create a new thread is familiar to everyone, so what is the relationship between thread and runnable? Let's first look at the following example.

public class ThreadTest {public
static void Main (string[] args) {for
(int i =; I < i++) {
SYSTEM.OUT.P Rintln (Thread.CurrentThread (). GetName () + "" + i);
if (i = =) {
Runnable myrunnable = new myrunnable ();
Thread thread = new Mythread (myrunnable);
Thread.Start ();
}}} Class Myrunnable implements Runnable {
private int i =;
@Override public
Void Run () {
System.out.println ("myrunnable Run");
for (i =; I < i++) {
System.out.println (Thread.CurrentThread (). GetName () + "" + i);
}
}}
class Mythread extends Thread {
private int i =;
Public Mythread (Runnable Runnable) {
super (Runnable);
}
@Override public
Void Run () {
System.out.println ("mythread run");
for (i =; I < i++) {
System.out.println (Thread.CurrentThread (). GetName () + "" + i);
}

Similarly, it is similar to creating threads for implementing runnable interfaces, except that

 

So is this a good way to create a new thread? The answer is yes. As for the thread execution body at this point is the run () method in the Myrunnable interface or the run () method in the Mythread class? Through the output we know that the thread execution body is the run () method in the Mythread class. The reason is simple, because the thread class itself implements the Runnable interface, and the run () method is the first method defined in the Runnable interface.

Public interface Runnable {public
abstract void run ();

Let's look at the implementation of the Run () method in the thread class for the Runnable interface:

@Override public
Void Run () {
if (target!= null) {
target.run ();
}

That is, when you execute the run () method in the thread class, you first determine if the target exists, and you do so by executing the run () method in Target, which implements the Runnable interface and then writes the run () method in the class of the run () method. But the Liezi mentioned above, because of polymorphism, did not execute the run () method in the thread class at all, but directly executed the run-time type, i.e. the run () method in the Mythread class.

3. Create a thread using the callable and future interfaces. Specifically, you create the implementation class for the callable interface and implement the Clall () method. and use the Futuretask class to wrap the object of the callable implementation class and create the thread with this Futuretask object as target of the thread object.

It looks a bit complicated, and it's clear to see an example directly.

 public class ThreadTest {public static void main (string[] args) {callable<integer> mycal lable = new Mycallable (); Create Mycallable object futuretask<integer> ft = new futuretask<integer> (mycallable); Use Futuretask to wrap the Mycallable object for (int i = i < i++) {System.out.println (Thread.CurrentThread (). GetName () + "" + I
); if (i = =) {Thread thread = new Thread (ft); The//futuretask object creates a Thread.Start () as target of the thread object, and/or the thread enters the ready state} System.
Out.println ("Main thread for loop execution completed ..."); try {int sum = Ft.get ();//Get the result System.out.println ("sum =" + sum) returned by the call () method in the newly created new Thread;}
catch (Interruptedexception e) {e.printstacktrace ();} catch (Executionexception e) {e.printstacktrace ();}} Class Mycallable implements callable<integer> {private int i =;//Unlike the run () method, the call () method has a return value @Override public I
Nteger call () {int sum =; for (; I < i++) {System.out.println (Thread.CurrentThread (). GetName () + "" + i);
sum + = i;
return sum; }
} 

First, we find that in implementing the callable interface, this is no longer the run () method, but the call () method, which acts as a thread executor and also has a return value! When a new thread is created, it is wrapped by futuretask to wrap the Mycallable object and as target for the thread object. So look at the definition of the Futuretask class:

public class Futuretask<v> implements runnablefuture<v> {
//...
} 
Public interface runnablefuture<v> extends Runnable, future<v> {
void run ();

So, we find that the Futuretask class actually implements both the runnable and the future interface, which makes it have future and runnable dual characteristics. The runnable attribute allows you to target the thread object and future the attribute so that it can get the return value of the call () method in the newly created thread.

Executing this procedure, we find that sum = 4950 is always the last output. and "main thread for loop execution completed ..." It is most likely to be output in the middle of a child thread loop. By the CPU's thread-scheduling mechanism, we know that "main thread for loop execution completed ..." The timing of the output is not any problem, so why sum =4950 will always last output?

Because the Ft.get () method gets the return value of the child thread call () method, the Ft.get () method blocks until the call () method has finished executing to fetch the return value when the child thread has not finished executing the method.

This explains three common thread-creation methods, which are the start () method of the calling thread object for the thread's startup, and it is important to note that the start () method cannot be invoked on the same thread object two times.

Three. Java Multi-Threading readiness, operation, and death status

The ready state is converted to a running state: When this thread gets the processor resources;

The run state is converted to a ready state: When this thread actively invokes the yield () method or loses the processor resources during the run process.

The run state is converted to a dead state: When this thread thread execution completes or an exception occurs.

It is important to note here that when the yield () method of the thread is invoked, the thread transitions from the run state to the ready state, but the next thread in the CPU dispatch ready state has a certain randomness, so that a thread called the yield () method may appear. The CPU then still dispatches the case of a thread.

Because of the actual business needs, it is common to encounter the need to terminate a thread at a particular time, to bring it into a state of death. At present, the most common practice is to set a Boolean variable, when the condition is satisfied, so that the thread execution quickly completed. Such as:

public class ThreadTest {public
static void Main (string[] args) {
myrunnable myrunnable = new myrunnable ();
Thread thread = new Thread (myrunnable);
for (int i =; I < i++) {
System.out.println (Thread.CurrentThread (). GetName () + "" + i);
if (i = =) {
thread.start ();
}
if (i = =) {
myrunnable.stopthread ()
;
}
}}} Class Myrunnable implements Runnable {
private boolean stop;
@Override public
Void Run () {for
(int i =; I < &&!stop i++) {
System.out.println (Thread.curr Entthread (). GetName () + "" + i);
}
public void Stopthread () {
this.stop = true;
}
}

The above is a small series to introduce the Java thread Multithreading comprehensive analysis, I hope to help everyone, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.