Five states of the thread and three ways to change the state

Source: Internet
Author: User

1. New state: The thread object has been created and the start () method has not been invoked on it.

2. Operational status: When the thread is eligible to run, but the scheduler has not selected it as the state in which the thread is running. When the start () method is called, the thread first enters the operational state. After the thread has run or has returned from blocking, waiting, or sleeping, it returns to the operational state.

3. Running state: The thread Scheduler selects a thread from a running pool as the current thread is in the state of the thread. This is also the only way that a thread goes into a running state.

4. Wait/block/Sleep state: This is the state at which the thread is eligible to run. In fact, this three-state combination is one, and its common denominator is that the thread is still alive, but there is no condition to run at the moment. In other words, it is operational, but if an event occurs, he may return to the operational state.

5. Death state: When the thread's run () method finishes, it is considered dead. This thread object may be alive, but it is not a separate thread. Once a thread dies, it cannot be resurrected. If you call the start () method on a dead thread, the java.lang.IllegalThreadStateException exception is thrown.

1. Sleep

Thread.Sleep (Long Millis) and Thread.Sleep (long millis, int Nanos) static methods force the currently executing thread to hibernate (suspend execution) to "slow down the thread." When the thread sleeps, it sleeps somewhere and does not return to the operational state until it wakes up. When the sleep time expires, it returns to the operational state.

Reason for thread sleep: Thread execution is too fast, or it needs to be forced into the next round because Java specifications do not guarantee a reasonable rotation.

 Packagethread; Public classMulitytImplementsRunnable {PrivateString S; Private Longi = 1;  PublicMulityt (String s) { This. S =s; } @Override Public voidrun () {//TODO auto-generated Method Stub         while(I < 10) {System.out.println (s+ "=====" + i++);//Thread.yield ();            Try{Thread.Sleep (1000); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }        }    }     Public Static voidMain (string[] args)throwsinterruptedexception {mulityt m=NewMulityt ("a"); Thread T=NewThread (m);        T.start (); Mulityt m2=NewMulityt ("B"); Thread T2=NewThread (m2);        T2.start (); Mulityt M3=NewMulityt ("C"); Thread T3=NewThread (m3);            T3.start (); }}

Output: (Pause for about one second after each round of output)

A=====1b=====1C=====1b=====2a=====2C=====2C=====3a=====3b=====3a=====4C=====4b=====4a=====5C=====5b=====5a=====6C=====6b=====6b=====7a=====7C=====7b=====8a=====8C=====8C=====9a=====9b=====9

1. Thread sleep is the best way to help all threads get the chance to run.

2, thread sleep expires automatically wake up and return to the operational state, not the running state. The time specified in sleep () is the shortest time the thread will not run. Therefore, the sleep () method does not guarantee that the thread will start executing after the sleep expires.

3. Sleep () is a static method that only controls the currently running thread.

2. Thread priority and thread concession yield ()

A thread's concession is achieved by Thread.yield (). The yield () method acts by suspending the currently executing thread object and executing other threads.

To understand yield (), you must understand the concept of thread precedence. The thread always has a priority and the priority range is between 1~10. The JVM thread Scheduler is a priority-based preemptive scheduling mechanism. In most cases, the currently running thread priority will be greater than or equal to the priority of any thread in the thread pool. But that's just the majority of the situation.

Note: When designing multithreaded applications, be sure not to rely on the priority of the thread. Because thread scheduling priority operations are not guaranteed, thread precedence can only be used as a way to improve program efficiency, but ensure that the program does not rely on such operations.

When thread pool threads have the same priority, the Scheduler's JVM implementation is free to select the thread it likes. There are two possible actions for the scheduler: one is to select a thread to run until it blocks or runs. The second is the Time Shard, which provides equal running opportunities for each thread in the pool.

The Thread.yield () method acts by suspending the currently executing thread object and executing other threads.

Yield () should be done to get the current running thread back to the operational state to allow other threads with the same priority to get the run opportunity. Therefore, the purpose of using yield () is to allow appropriate rotation between threads of the same priority. However, in practice there is no guarantee that yield () will be compromised, as the thread of the concession may be checked again by the thread scheduler.

 Packagethread; Public classMulitytImplementsRunnable {PrivateString S; Private Longi = 1;  PublicMulityt (String s) { This. S =s; } @Override Public voidrun () {//TODO auto-generated Method Stub         while(I < 10) {System.out.println (s+ "=====" + i++);        Thread.yield (); }    }     Public Static voidMain (string[] args)throwsinterruptedexception {mulityt m=NewMulityt ("a"); Thread T=NewThread (m);        T.start (); Mulityt m2=NewMulityt ("B"); Thread T2=NewThread (m2);        T2.start (); Mulityt M3=NewMulityt ("C"); Thread T3=NewThread (m3);            T3.start (); }}

Output Result:

A=====1C=====1b=====1C=====2a=====2b=====2C=====3a=====3b=====3C=====4a=====4b=====4C=====5a=====5b=====5C=====6a=====6b=====6C=====7b=====7a=====7C=====8b=====8C=====9a=====8b=====9a=====9

Conclusion: Yield () never causes the thread to go to the wait/sleep/block state. In most cases, yield () will cause the thread to go from the running state to the operational state, but it may not be effective.

3. Join () method

The non-static method of thread join () lets a thread B "join" to the tail of another thread A. b does not work until a is complete.

In addition, the join () method also has an overloaded version with a time-out limit. For example, T.join (5000); Let the thread wait for 5000 milliseconds, and if it exceeds this time, stop waiting and become a running state.

 Packagethread; Public classMulitytImplementsRunnable {PrivateString S; Private Longi = 1;  PublicMulityt (String s) { This. S =s; } @Override Public voidrun () {//TODO auto-generated Method Stub         while(I < 10) {System.out.println (s+ "=====" + i++); }    }     Public Static voidMain (string[] args)throwsinterruptedexception {mulityt m=NewMulityt ("a"); Thread T=NewThread (m);        T.start (); Mulityt m2=NewMulityt ("B"); Thread T2=NewThread (m2);        T2.start ();        T2.join (); Mulityt M3=NewMulityt ("C"); Thread T3=NewThread (m3);            T3.start (); }}

Output Result:

A=====1b=====1a=====2b=====2a=====3b=====3a=====4a=====5b=====4a=====6b=====5a=====7b=====6a=====8b=====7a=====9b=====8b=====9C=====1C=====2C=====3C=====4C=====5C=====6C=====7C=====8C=====9

Summary:

To the current location, there are 3 ways to get the thread out of the running state:

1. Call Thread.Sleep (): Causes the current thread to sleep at least a few milliseconds (although it may be interrupted before the specified time).

2. Call Thread.yield (): There is no guarantee for too many things, although it usually brings the current running thread back to the operational state, allowing threads with the same priority to execute.

3. Call the Join () method: Ensure that the current thread stops executing until the thread to which the thread is joined is complete. However, if the thread it joins does not survive, the current thread does not need to stop.

Five states of the thread and three ways to change the state

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.