[Java concurrent programming]-six states of threads and their state transitions

Source: Internet
Author: User

1. Thread's own information

The process of running a thread produces a lot of information, which is stored in the member variables in the thread class, which are common:
a. The ID of the thread is uniquely identified getid ()
b. The name of the thread: GetName (), if you do not set the thread name to default to "Thread-xx"
c. Thread priority: GetPriority, thread priority from 1-10, where the larger the number indicates higher priority, and the more likely the JVM is scheduled to execute, the JDK has three common statuses built into it:

Min-Priority public final static int min_priority = 1;//General priority public final static int norm_priority = 5;//Maximum priority public final Stati c int max_priority = 10;

It is generally not recommended to set the priority of a thread, and a IllegalArgumentException exception will occur if an illegal priority program is set.

2. Several states of the thread 1. There are six states of Java threads
public enum state {    //Line Cheng Gang creation     NEW,     //the thread that is running in the JVM     runnable,    //the thread is blocking, waiting for a monitoring lock, You can perform a     blocked,    //wait state     waiting in a synchronized code block,     //calling the Sleep ()  join ()  wait () method may cause the thread to be in a wait state     timed_waiting , the     //thread has finished executing and has exited     terminated;} 

The above six status graphs are as follows:
650) this.width=650; "Src=" http://www.sxt.cn/editor/attached/image/20150415/518242891/ 359892b3-8f98-4848-8cdd-4a8f7f1396f8.jpg "width=" "height=" 260 "alt=" Picture name "style=" Margin:0px;padding:0px;border : 0px None;background:rgb (244,247,249) None repeat scroll 0px 0px; "/>

2. Explanation of Thread Status

1. When the thread inherits the thread or implements Runnable, the thread enters its initial state after the new thread object has been created.

2. When the thread object invokes the start () method, the thread starts to enter a running state.

3. After the thread enters the operational state, if the logic completes then the thread will be terminated, and if it is not finished, the intermediate JVM allocates time slices to run out and will go into a running state, which executes immediately once the thread is selected by the JVM.

4. Operation status is more complicated
First : If the thread completes the logic after executing the run () main () method, the thread enters terminated

second : When a thread calls sleep () or the Join () method enters the blocked state, it is important to note that the blocked thread does not release the current system resources, when sleep () ends or join () waits for another thread to arrive, The current thread enters the runnable state waiting for the JVM to allocate resources.

Third : When the thread enters the runnable state, but has not yet started to run, it is found that the required resources are in a synchronous state synchronized, this time the thread will enter the WAITING,JVM will use the queue to control these threads, Threads that are both advanced and time waiting will get the JVM resources to execute into the waiting

Fourth : If the thread in runnable calls yield () yields the JVM resource, it will enter the new state and the other new state threads to compete for re-entry runnable

Fifth : If the current thread calls the Wait () method, the current thread enters time waiting but at this point the current thread frees the occupied JVM resources, which cannot be automatically awakened after entering this state, and must be called notify () or Notifyall () method, the thread enters waiting.

3. Case explanation
 case: Explain the six running states of a thread with a case where the pig class implements the Runnable interface, which is the logic to print the currently running thread information once every second. Starting 10 pig threads in the main method sets the corresponding thread priority level, and saves the initial thread state to the thread state array, which determines whether the current thread state and the initial state are the same, and if different, prints the current thread's information to the log file. 
class pig implements runnable {     @Override      Public void run ()  {        for  (int i =  0; i < 10; i++)  {             try {                 //thread sleeps for one second                  timeunit.seconds.sleep (1);             } catch  (interruptedexception e)  {                 e.printstacktrace ();             }            // Prints the current execution thread information              system.out.println ("threadname : "  +  Thread.CurrentThread (). GetName ());         }    }} Public class app {    public static void main (String[]  args)  throws Exception {        //  create an off-the-shelf array          Thread[] taskArr = new Thread[10];         //  Thread State Array         thread.state [] threadstates = new thread.state[10];        //   Set the state of a thread         for  (int i = 0; i  < 10; i++)  {            taskarr[ I] = new&nbsP Thread (New pig ());            //  set state separately             if  ((i % 3)  ==  0)  {                 taskarr[i].setpriority (thread.norm_priority);             } else if  ((i % 3)  == 1)  {                 taskarr[i].setpriority (Thread.MIN_ Priority);            } else if  ((i  % 3)  == 2)  {                 taskarr[i].setpriority (thread.max_priority);             }         }        //  Write thread information to a file for easy analysis         FileWriter fWriter = new  FileWriter (". \\log.txt");        printwriter pwriter =  New printwriter (fwriter);        //  loop traversal get thread info          for  (int i = 0; i < 10; i++) &NBSP;{&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;PWRITER.PRINTLN ("Thread  "  + i +  "  Status:"  + taskarr[i].getstate ());             //  saves the current thread state to the state array              threadstates[i] = taskarr[i].getstate ();         }        //  start thread         for  (int  i = 0; i < 10; i++)  {             taskarr[i].start ();        }         //  writes a state change process to a file if the state of the thread is different from the initial state during Operation          boolean finish = false;        while   (!finish)  {            for  (int  i = 0; i < 10; i++)  {                 //  Thread status Changes                  if  (Taskarr[i].getstate ()  !=  Threadstates[i])  {                     / /  Print thread Current information                      printthreadmsg (Pwriter, taskarr[i], threadstates[i]);                     //   Saves the current thread state to the thread-state array                      threadstates[i] = taskarr[i].getstate ();                 }             }             finish = true;            for  (int  i = 0; i < 10; i++)  {                 finish = finish &&  (Taskarr[i].getstate ()  ==  state.terminated);            }         }    }    /** *  Print information about the current thread  *  @param  pWriter *  @param  thread *  @param  state */     private static void printthreadmsg (printwriter pwriter,  Thread thread, state state)  {         Pwriter.println ("*********************************************************");      &NBSP;&NBSP;&NBSP;PWRITER.PRINTLN ("Thread id: "  + thread.getid ()  +  "  Thread Name:"  +  thread.getname ()); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;PWRITER.PRINTLN ("Thread Priority:"  + thread.getpriority ());      &NBSP;&NBSP;&NBSP;PWRITER.PRINTLN ("Thread past state:"  + state);        &NBSP;PWRITER.PRINTLN ("Thread Current state:"  + thread.getstate ());         pwriter.println ("*********************************************************");     }}

Partial execution results are as follows:
650) this.width=650; "Src=" http://www.sxt.cn/editor/attached/image/20150415/518242891/ Ad5dd1b6-6c1d-4076-841a-04c8c7b3714c.jpg "Width=" 260 "height=" "alt=" Picture name "style=" Margin:0px;padding:0px;border : 0px None;background:rgb (244,247,249) None repeat scroll 0px 0px; "/>

Analysis of the above partial execution results shows that when the pig thread sleeps, it causes the transformation of other thread states, where the past state and the current state can significantly react to the outgoing state switch.


This article is from the "No Water Fish" blog, please be sure to keep this source http://javaqun.blog.51cto.com/10687700/1703226

[Java concurrent programming]-six states of a thread and its state transitions

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.