Java Multithreading (1) Create

Source: Internet
Author: User
Tags thread class

I. Thread life cycle and five basic states

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

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 calling the Thread object's start () method (T.start ();). The thread enters the ready state. A thread in the ready state simply means that the thread is ready. Wait for CPU scheduling to run at any time. It is not said that running the T.start () this thread will run immediately;

execution State (Running): When the CPU starts scheduling a thread in the ready state. At this point the thread can actually execute, that is, go to execution state. Note: The ready state is the only entry into the execution state, that is, the thread wants to go into execution state execution. Must be in the ready state first;

blocking State (Blocked): A thread that is in the execution state temporarily abandons the use of the CPU for some reason. Stop execution. At this point the blockage is entered. Until it enters the ready state, there is a chance to be called again by the CPU to enter the execution state.

Depending on the cause of the blockage. The blockage state can be divided into three kinds:

1. Wait for the plug: The thread in the execution state executes the wait () method. Causes this thread to enter the waiting block state.

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

3. Other blockages-the thread enters a blocked 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 when I/O processing is complete. The thread is once again in a ready state.

"Question": Lock holding problem

dead State (Dead): The thread runs out 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. Override the Run () method of the class.

1 classMyThreadextendsThread {2     3     Private inti = 0;4 5 @Override6      Public voidrun () {7          for(i = 0; i < i++;) {8System.out.println (Thread.CurrentThread (). GetName () + "" +i);9         }Ten     } One}

1  Public classThreadTest {2 3      Public Static voidMain (string[] args) {4          for(inti = 0; I < 100; i++) {5System.out.println (Thread.CurrentThread (). GetName () + "" +i);6             if(i = = 30) {7Thread MyThread1 =NewMyThread ();//Create a new thread myThread1 this thread into the new state8Thread myThread2 =NewMyThread ();//Create a new thread myThread2 this thread into the new state9Mythread1.start ();//call the Start () method to allow the thread to enter the ready stateTenMythread2.start ();//call the Start () method to allow the thread to enter the ready state One             } A         } -     } -}

As seen above, inheriting the thread class, by overriding the run () method, defines a new thread class Mythread, in which the method body of the run () method represents the task that the thread needs to complete. Called the thread-running 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 does not necessarily run 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 the same as the thread run body, creates an instance of the Runnable implementation class, and creates a thread object with this instance as the target of the thread class, which is the true thread object.

1 classMyrunnableImplementsRunnable {2     Private inti = 0;3 4 @Override5      Public voidrun () {6          for(i = 0; i < i++;) {7System.out.println (Thread.CurrentThread (). GetName () + "" +i);8         }9     }Ten}
1  Public classThreadTest {2 3      Public Static voidMain (string[] args) {4          for(inti = 0; I < 100; i++) {5System.out.println (Thread.CurrentThread (). GetName () + "" +i);6             if(i = = 30) {7Runnable myrunnable =NewMyrunnable ();//create an object of the Runnable implementation class8Thread Thread1 =NewThread (myrunnable);//Create a new thread with myrunnable as the thread target9Thread thread2 =NewThread (myrunnable);TenThread1.start ();//call the Start () method to allow the thread to enter the ready state One Thread2.start (); A             } -         } -     } the}

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

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 () {        ifnull) {            target.run ();        }    }

That is, when you run to the run () method in the thread class, you first infer whether the target exists. exists run the run () method in Target, which is the run () method in the class that implements the Runnable interface and re-writes the Run () method. But the above-mentioned sake, because polymorphic existence. Instead of running to the run () method in the thread class, run the run-time type, the Mythread class, directly first.


3. Create a thread using the callable and future interfaces. In detail is the implementation class that creates the callable interface and implements the Clall () method.

and use the Futuretask class to wrap the object of the callable implementation class. And this Futuretask object is used as the target of the thread object to create the thread.


Looking at it as if it's a bit complicated, just to see the example is clear.

   1   Public classThreadTest {2 3      Public Static voidMain (string[] args) {4 5Callable<integer> mycallable =NewMycallable ();//Create a Mycallable object6futuretask<integer> ft =NewFuturetask<integer> (mycallable);//use Futuretask to wrap mycallable objects7 8          for(inti = 0; I < 100; i++) {9System.out.println (Thread.CurrentThread (). GetName () + "" + i);Ten             if(i = = 30) { OneThread thread =NewThread (FT);//The Futuretask object creates a new thread as the target of the thread object AThread.Start ();//thread goes into ready state -} -} the  -System.out.println ("Main thread for loop run complete."); -          -         Try{ +             intsum = Ft.get ();//Gets the result returned by the call () method in the newly created new thread -System.out.println ("sum =" + sum); +}Catch(Interruptedexception e) { AE.printstacktrace (); at}Catch(Executionexception e) { -E.printstacktrace (); -} -  -} -} in  -  to classMycallableImplementscallable<integer> { +     Private inti = 0; -  the     //Unlike the Run () method. The call () method has a return value *@Override $      PublicInteger Call () {Panax Notoginseng         intsum = 0; -          for(; i <; i++) { theSystem.out.println (Thread.CurrentThread (). GetName () + "" + i); +sum + = i; A} the         returnSum +} -  $}

First, we find that. In the implementation callable interface. This is no longer the run () method, but instead the call () method, which is the thread-running body and also has a return value at the same time. When creating a new thread, the Mycallable object is wrapped by Futuretask, and at the same time as the target of the thread object.

So look at the definition of the Futuretask class:

1  Public class Implements runnablefuture<v> {2     3     //.... 4     5 }
1  Public Interface extends Runnable, future<v> {2     3     void run ();  4     5 }

So. We found that the Futuretask class actually implemented the runnable and future interfaces at the same time, thus making it a dual feature of future and runnable. With the runnable feature, it can be used as the target of the thread object. The future feature enables it to obtain the return value of the call () method in the newly created thread.

Run this program. We find that sum = 4950 is always the last output.

Instead, the main thread for loop runs complete. It is very likely that the output is in the middle of the child thread loop. By the CPU's thread scheduling mechanism, we know that the "main thread for loop run is complete ..." The timing of the output is no matter what the problem, then why the sum =4950 will be the last output forever?

The reason is that when you get the return value of a child thread call () method through the Ft.get () method. When the child thread is not finished running, the Ft.get () method is blocked until the call () method runs to the completion ability to fetch the return value.

These are the main explanations for the three common thread creation methods for thread initiation. is the start () method that invokes the thread object. It is important to note that the start () method cannot be called two times on the same thread object



Java Multithreading (1) Create

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.