Java Summary series: Java Multithreading (i)

Source: Internet
Author: User
Tags thread class

Multithreading as a very important point of knowledge in Java, there is still a need to summarize.

I. Thread life cycle and five basic states

For the life cycle of the threads in Java, first look at this more classic diagram:

Basically includes all the important knowledge points of multithreading in Java. Mastered the knowledge points in Java, multithreading is basically mastered. Mainly include:

Java threads have v basic state

new State (new): when the thread object pair is created, it enters the new state, such as thread t = new MyThread ();

ready State (Runnable): when the Start () method (T.start ()) of the thread object is called, the thread enters the ready state. A thread that is in a ready state simply means that the thread is ready to wait for CPU scheduling to execute, not to say that the T.start () thread executes immediately;

Run State (Running): When the CPU starts scheduling a thread in the ready state, the thread is actually executing, which is going into the running state. Note: The ready state is the only entry into the running state, that is, the thread must first be in a ready state if it wants to execute in a running state;

blocking State (Blocked): A thread that is in the running state temporarily abandons the use of the CPU for some reason, stops execution, and then enters a blocking state until it enters the ready state, and is then given 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 types:

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

2. Synchronization blocking--the thread acquires the synchronized synchronization lock failure (because the lock is occupied by another thread), it will enter the synchronization blocking state;

3. Other blocking-the thread will go into a blocking state by calling the thread's sleep () or join () or making an I/O request. When the sleep () state times out, join () waits for the thread to terminate or time out, or the I/O process finishes, the thread is re-entered in a ready state.

dead State (Dead): The thread finishes executing or exits the run () method because of an exception, and the thread ends the life cycle.

Two. Java multi-threading creation and startup

The creation of threads in Java is common in three basic forms

1. Inherit the thread class, overriding the run () method of the class.

1 class MyThread extends Thread {2      3     private int i = 0; 4  5     @Override 6 public     void Run () {7         for (i = 0; i <; i++) {8             System.out.println (Thread.CurrentThread (). GetName () + "" + i); 9         }10     }11}
1 public class ThreadTest {2  3 publicly     static void main (string[] args) {4 for         (int i = 0; i <; i++) { 5             System.out.println (Thread.CurrentThread (). GetName () + "" + i); 6             if (i = =) {7                 Thread myThread1 = new MyThread ();     Create a new thread  myThread1  This thread into the new state 8 thread                 myThread2 = new MyThread ();     Create a new thread myThread2 this thread into the new state 9                 Mythread1.start ();                     Calling the start () method causes the thread to enter a ready state of                 Mythread2.start ();                     Call the Start () method to allow the thread to enter the ready state one by one             }12         }13     }14}

As shown above, inheriting the thread class, by overriding the run () method, defines a new thread class Mythread, where the method body of the run () method represents the task that the thread needs to complete, called the thread-executing body. When this thread class object is created, a new thread is created and enters the new state of the thread. By invoking the start () method referenced by the thread object, the thread enters the ready state, and the thread is not necessarily executed immediately, depending on the timing of the CPU schedule.

2. Implement the Runnable interface and override the run () method of the interface, the run () method is also the thread execution body, create an instance of the Runnable implementation class, and use this instance as the target of the thread class to create the thread object. This thread object is the real thread object.

1 class Myrunnable implements Runnable {2     private int i = 0; 3  4     @Override 5 public     void Run () {6         fo R (i = 0; i < i++) {7             System.out.println (Thread.CurrentThread (). GetName () + "" + i); 8         } 9     }10}
1 public class ThreadTest {2  3 publicly     static void main (string[] args) {4 for         (int i = 0; i <; i++) { 5             System.out.println (Thread.CurrentThread (). GetName () + "" + i); 6             if (i = =) {7                 Runnable myrunnable = new myrunnable ();//Create an object of the Runnable implementation Class 8                 thread thread1 = new Thread (myrunnable); Create a new thread with myrunnable as thread target 9 thread                 thread2 = new Thread (myrunnable),                 Thread1.start ();//Call Start () method allows the thread to enter the ready state one by one                 Thread2.start ();             }13         }14     }15}

I believe the two ways to create new threads are familiar to everyone, so what is the relationship between thread and runnable? Let's look at the following example first.

 1 public class ThreadTest {2 3 publicly static void main (string[] args) {4 for (int i = 0; i <; i++) {5 System.out.println (Thread.CurrentThread (). GetName () + "" + i); 6 if (i = =) {7 Runnable myrunnable = new Myrunnable (); 8 Thread thread = N EW MyThread (myrunnable);     9 Thread.Start ();}11}12}13}14 class Myrunnable implements Runnable {16         private int i = 0;17 @Override19 public void Run () {System.out.println ("in myrunnable Run"); 21         for (i = 0; i < i++) {System.out.println (Thread.CurrentThread (). GetName () + "" + i); 23 }24}25}26 class MyThread extends Thread {+/-private int i = 0;30 to public MyThread (Runnable run nable) {runnable),}34 @Override36 public void Run () {PNS System.out.println ("in M Ythread run "); (i = 0; I &lT 100; i++) {System.out.println (Thread.CurrentThread (). GetName () + "" + i); 40}41}42}

Similarly, the implementation of the Runnable interface is similar to creating threads, where the difference lies in

1 Thread thread = new MyThread (myrunnable);

So is this a good way to create a new thread? The answer is yes. As to whether the thread-executing body at this point is the run () method in the Myrunnable interface or the run () method in the Mythread class? By outputting we know that the thread executor 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 first defined in the Runnable interface.

1 public interface Runnable {2    3 public     abstract void Run (); 4     5}

Let's take a 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 executing to the run () method in the thread class, it is first judged whether the target exists, and the run () method in the class that implements the Runnable interface and the Run () method is implemented in the run () method. However, due to the existence of polymorphism, the sake does not execute the run () method in the thread class, but instead executes the run-time type, the Mythread class, directly.

3. Create a thread using the callable and future interfaces. Specifically, you create an 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 the target of the thread object.

Look at it as if it's a little complicated, just to see an example is clear.

 1 public class ThreadTest {2 3 public static void main (string[] args) {4 5 callable<integer> Mycall    able = new mycallable (); Create Mycallable Object 6 futuretask<integer> ft = new futuretask<integer> (mycallable); Use Futuretask to wrap mycallable Objects 7 8 for (int i = 0; i <; i++) {9 System.out.println (Thread.curr   Entthread (). GetName () + "" + i), if (i = =) {One thread thread = new Thread (ft);                      The Futuretask object creates a new thread as the target of the thread object, Thread.Start (); Thread enters ready state}14}15 System.out.println ("Main thread for loop execution completed ...");            + try {int sum = Ft.get (); Gets the result returned by the call () method in the newly created new thread, System.out.println ("sum =" + sum); \ n} catch (Interruptedexception e) {2         2 E.printstacktrace (); executionexception catch (E) {e.printstacktrace (); 25    }26 27 }28}29-Class Mycallable implements callable<integer> {+-private int i = 0;33 34//Unlike the run () method, Cal             The L () method has a return value of @Override36 public Integer call () {PNS int sum = 0;38 for (; i <; i++) {39 System.out.println (Thread.CurrentThread (). GetName () + "" + i), sum of + = i;41}42 Retu RN sum;43}44 45}

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

1 public class Futuretask<v> implements runnablefuture<v> {2     3     //.... 4     5}
1 public interface runnablefuture<v> extends Runnable, future<v> {2     3     void Run (); 4     5}

As a result, we find that the Futuretask class actually implements both the runnable and the future interfaces, thus making it a dual feature of future and runnable. The runnable attribute can be used as the target of the thread object, and the future attribute allows it to obtain 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 the main thread for loop is finished ... is likely to be output in the middle of a child thread loop. By the CPU's thread scheduling mechanism, we know that "the main thread for loop is finished ..." The timing of the output is no problem, then why is the sum =4950 always the last output?

The reason is that when you get the return value of a child thread call () method through the Ft.get () method, the Ft.get () method blocks until the call () method finishes executing before the child thread has finished executing the method.

The above mainly explains three kinds of common thread creation, for thread start-up, is called the Thread object's start () method, need to pay special attention to: cannot call the start () method on the same thread object two times.

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

Ready state transitions to run state: When this thread gets processor resources;

The run state transitions to ready state: When this thread actively calls the yield () method or loses the processor resources during the run.

The running state transitions to a dead state: The execution of this thread thread is complete or an exception has occurred.

It is important to note that when a thread's yield () method is called, the thread transitions from the running state to the ready state, but which thread in the CPU dispatch readiness State is in a certain randomness, so that a thread may appear after the yield () method is called. The CPU then still dispatches the A-thread case.

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

1 public class ThreadTest {2  3 public     static void Main (string[] args) {4  5         myrunnable myrunnable = new M Yrunnable (); 6         Thread thread = new Thread (myrunnable), 7          8 for         (int i = 0; i < i++) {9             System.out.println (thre Ad.currentthread (). GetName () + "" + i),             if (i = =) {One                 Thread.Start (), and             }13             if (i = =) {                 m Yrunnable.stopthread ();             }16         }17     }18}19 class Myrunnable implements Runnable {     Boolean stop;23     @Override25 public     void Run () {         (int i = 0; i < &&!stop; i++) {27< C20/>system.out.println (Thread.CurrentThread (). GetName () + "" + i);         }29     }30 to public     void Stopthread () {         this.stop = true;33     }34 35}

Java Summary series: Java Multithreading (i)

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.