Beginners Learn Java (11)-Multithreading----The life cycle of threads

Source: Internet
Author: User

      • New and ready states
      • Run state and blocking state
      • Thread death

When a thread is created and started, it is not in the first state of execution and is not always running. Threads also have a life cycle, including: Create (New), Ready (Runnable), Block (Blocked), run (Running), Death (Dead) five states. When a thread is running, it is not always possible to occupy the CPU running alone, but to always switch between running and ready state.

New and ready states

When the program creates a thread from new, the thread is in the new state, but at this point the thread does not show any characteristics of the threads, and as with other ordinary Java objects, the Java Virtual machine allocates memory for it and initializes the values of its variables.

When the thread object calls the start () method, the thread is in a ready state, and the Java Virtual machine creates a method call stack and a program counter for it, and the thread indicates that it can run, but when it runs, it waits for the JVM to dispatch.

There is a need to note that starting a thread needs to call the start () method, rather than using run () to start the thread, if you call the Run method directly, the system will treat the thread as a normal object, run () Method is just an ordinary method. Give us a chestnut:

 PackageLifecycle Public  class invokerun extends Thread{    Private intI Public void Run(){ for(;i< -; i++) {System.out.println (Thread.CurrentThread (). GetName () +" "+i); }    } Public Static void Main(string[] args) { for(intI=0;i< -; i++) {System.out.println (Thread.CurrentThread (). GetName () +" "+i);if(i== -){NewInvokerun (). run ();NewInvokerun (). run (); }        }    }}

When the thread is started, the run() method is used, and the end result is that the entire program runs on only one thread. The program has been programmed with a single thread. The main reason is that when you start a thread, if you invoke the method start() , the system treats the run() method as the thread's executor. If you call the run() method directly, run() other threads cannot run concurrently until the method returns.

The start () method can only be called on a thread that is in the new state, or a Illegalthreadstateexception exception will be thrown

Run state and blocking state

When a ready thread gets the CPU, it goes into the running state, and if the system has only one CPU, multiple threads are rotated on the same CPU, and a CPU is running at any time with only one thread. If there is more than one CPU, there will be multiple threads parallel (parallel) execution;
A thread cannot be running until the thread is able to perform in a short amount of time, otherwise the thread will be interrupted several times during execution, in order to give the other threads the opportunity to execute, and to consider the execution strategy in the background.

is the state transition diagram of the thread, through which we can understand what conditions the thread is entering into the blocking (Blocked) state, and under what conditions to enter the ready (Runnable) state; By the same point, the thread is not going directly from the running state to the ready state, except yield() Method.

Thread death

The thread ends in the following three ways, ending with a dead state.

    1. run()Or call() the method execution completes and the thread ends normally.
    2. The thread throws an uncaught Exception or Error .
    3. Call the thread's stop() method directly to end the thread--the method is usually prone to deadlocks and is not recommended.

When the thread dies, the other threads are not affected and end. After the other child threads are started, their status and the main thread are equivalent and are not affected by the main thread.

How do I test if a thread has died? Measured by the method of the thread object, when the isAlive() thread is in the ready, running, blocking state, the returned result is true when the thread is in the dead, new state false . Here is an example of invoking a method on a dead thread start() :

 PackageStartdead; Public  class startdead extends Thread {    Private intI Public void Run(){ for(;i< -; i++) {System.out.println (GetName () +" "+i); }    }/** * @param args * *     Public Static void Main(string[] args) {Startdead SD =NewStartdead (); for(intI=0;i< -; i++) {System.out.println (Thread.CurrentThread (). GetName () +" "+i);if(i== -) {Sd.start ();            System.out.println (Sd.isalive ()); }//When i>20, the thread must have started, if Sd.isalive () is false, that is the state of death;            if(i> -&&!sd.isalive ()) {//Try to start the thread againSd.start (); }        }    }}

Calling a method on a thread that is already dead start() throws a illegalthreadstateexception exception.

in"main" java.lang.IllegalThreadStateException    at java.lang.Thread.start(Thread.java:595)    at startDead.StartDead.main(StartDead.java:27)

Do not attempt to invoke the start () method on a thread that is already dead, death is death, and the thread of death is not again considered the thread's executor. The program can only call the start () method on a thread that is in the new state, and it is also wrong to call start () two times for a thread that is in the new state, which throws a illegalthreadstateexception exception

Beginners Learn Java (11)-Multithreading----The life cycle of threads

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.