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

Source: Internet
Author: User

1 more content to see my other blog: http://blog.csdn.net/unikylin/article/details/45050823

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:

1//min Priority 2 public final static int min_priority = 1;3 4//General priority 5 Public final static int norm_priority = 5;6 7//Maximum priority 8 PU Blic final static 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
1 public enum State {2/     /Line Cheng Gang create 3     NEW, 4  5     //thread running in JVM 6     RUNNABLE, 7 8//     thread is blocking, waiting for monitoring lock, Can be re-synchronized code block execution 9     blocked,10//     wait status     waiting,13     //Call Sleep () join () Wait () method may cause thread to wait state 15     timed_waiting,16     //thread execution completed, has exited     terminated;19}

The above six status graphs are as follows:

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
案例:用案例解释线程的六种运行状态,其中Pig类实现Runnable接口,逻辑是打印当前运行的线程信息,每隔一秒打印一次。在Main方法中启动十个Pig线程设置相应的线程优先级别,并且将初始的线程状态保存到线程状态数组中,在运行的过程判断当前线程状态和初始状态是否相同,如果不同则打印当前线程的信息保存到日志文件中。
 1 class Pig implements Runnable {2 3 @Override 4 public void Run () {5 for (int i = 0; i <; i++) {6 try {7//thread sleeps one second 8 TimeUnit.SECONDS.sleep (1); 9} catch (Int Erruptedexception e) {e.printstacktrace (); 11}12//print current execution thread information Sys     Tem.out.println ("ThreadName:" + thread.currentthread (). GetName ());}15}16}17 public class App {19 public static void Main (string[] args) throws Exception {20//create off-the-shelf array thread[] Taskarr = new THREAD[10] ; 22 23//thread state array thread.state[] threadstates = new THREAD.STATE[10];25 26//Set thread status F             or (int i = 0; i < i++) {Taskarr[i] = new Thread (new Pig ()); 29 30//Set status 31 respectively 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].setprior ity (thread.max_priority); 37}38}39 40//writes thread information to a file for easy analysis. FileWriter Fwriter = new F Ilewriter (". \\log.txt"); PrintWriter pwriter = new PrintWriter (fwriter); 43 44//Loop traversal get thread information             or (int i = 0; i < i++) {pwriter.println ("thread" + i + "state:" + taskarr[i].getstate ()); 47 48 Saves the current thread state to an array of states threadstates[i] = Taskarr[i].getstate (); 50}51 52//Start thread-fo R (int i = 0; i < i++) {Taskarr[i].start (); 55}56 57//During operation if the state of the thread is different from the initial state, the state is changed                  The process is written to the file. 0 Boolean finish = false;59 (!finish) {size for (int i =; i <; i++) {62 Thread state Changes if (taskarr[i].getstate ()! = Threadstates[i]) {64//Print                Thread Current Information 65     Printthreadmsg (Pwriter, Taskarr[i], threadstates[i]); 66 67//Save the current thread state to the thread State array 68             Threadstates[i] = Taskarr[i].getstate ();}70}71 finish = true;72 for (int i = 0; I <) {i++ = Finish && (taskarr[i].getstate () = = State.terminat      ED); 74}75}76}77 78/**79 * Print information about the current thread * @param pWriter81 * @param thread82 * @param state83 */84 private static void Printthreadmsg (PrintWriter pwriter, thread thread, state state) {8  5 pwriter.println ("*********************************************************"); Pwriter.println ("Thread ID:") + Thread.getid () + "thread Name:" + thread.getname ()), PWRITER.PRINTLN ("Thread Priority:" + thread.getpriority ()); RITER.PRINTLN ("Thread past status:" + state), pwriter.println ("Thread Current state:" + thread.getstate ()), PWRITER.PRINTLN ("* * * ************************"); 91}92} 

Partial execution results are as follows:

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.

[Java concurrent programming]-six states of threads and their 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.