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

Source: Internet
Author: User

转载请注明: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:

//最小优先级publicfinalstaticint1;//一般优先级publicfinalstaticint5;//最大优先级publicfinalstaticint10;

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
publicenum State {    //线程刚创建    NEW,    //在JVM中正在运行的线程    RUNNABLE,    //线程处于阻塞状态,等待监视锁,可以重新进行同步代码块中执行    BLOCKED,    //等待状态    WAITING,    //调用sleep() join() wait()方法可能导致线程处于等待状态    TIMED_WAITING,    //线程执行完毕,已经退出    TERMINATED;}

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线程设置相应的线程优先级别,并且将初始的线程状态保存到线程状态数组中,在运行的过程判断当前线程状态和初始状态是否相同,如果不同则打印当前线程的信息保存到日志文件中。
Class Pig implements Runnable {@Override     Public void Run() { for(inti =0; I <Ten; i++) {Try{//thread sleeps for one secondTimeUnit.SECONDS.sleep (1); }Catch(Interruptedexception e)            {E.printstacktrace (); }//print current execution thread informationSystem.out.println ("ThreadName:"+ Thread.CurrentThread (). GetName ()); }    }} Public  class App {     Public Static void Main(string[] args)throwsException {//Create an off-the-shelf arraythread[] Taskarr =Newthread[Ten];//thread state arraythread.state[] Threadstates =Newthread.state[Ten];//Set the state of the thread         for(inti =0; I <Ten; i++) {Taskarr[i] =NewThread (NewPig ());//Set status 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 analysisFileWriter Fwriter =NewFileWriter (". \\log.txt"); PrintWriter pwriter =NewPrintWriter (Fwriter);//Loop through the Get thread information         for(inti =0; I <Ten; i++) {pwriter.println ("Threads"+ i +"Status:"+ taskarr[i].getstate ());//Saves the current thread state to the state arrayThreadstates[i] = Taskarr[i].getstate (); }//Start thread         for(inti =0; I <Ten;        i++) {Taskarr[i].start (); }writes a state change process to a file if the state of the thread is not the same as the initial state during the run        Booleanfinish =false; while(!finish) { for(inti =0; I <Ten; i++) {//thread state changed                if(Taskarr[i].getstate ()! = Threadstates[i]) {//Print thread current informationPrintthreadmsg (Pwriter, Taskarr[i], threadstates[i]);//Saves the current thread state to the thread state arrayThreadstates[i] = Taskarr[i].getstate (); }} finish =true; for(inti =0; I <Ten;            i++) {finish = Finish && (taskarr[i].getstate () = = state.terminated); }        }    }/** * Print information for current thread * @param pwriter * @param thread * @param  State */    Private Static void printthreadmsg(PrintWriter pwriter, thread thread, state state) {Pwriter.println ("*********************************************************"); Pwriter.println ("Thread ID:"+ Thread.getid () +"Thread Name:"+ Thread.getname ()); Pwriter.println ("Thread Priority:"+ thread.getpriority ()); Pwriter.println ("Thread past state:"+ state); Pwriter.println ("Thread Current state:"+ thread.getstate ()); Pwriter.println ("*********************************************************"); }}

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

Related Article

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.