Java thread (4): thread state conversion

Source: Internet
Author: User

SCJP5 Study Notes 1. State Transition of a thread state is the basis of thread control. The total thread status can be divided into five major states: active, dead, runable, running, waiting/blocking. 1. New State: the thread object has been created and the start () method has not been called on it. 2. Run Status: When the thread is eligible to run, but the scheduler has not selected it as the status of the thread when it is running. When the start () method is called, the thread first enters the runable state. After the thread is running or after it is returned from the blocking, waiting, or sleep status, it also returns to the runable status. 3. Running status: the thread scheduler selects a thread from the runable pool as the status of the current thread. This is the only way for a thread to enter the running state. 4. Waiting/blocking/sleep status: this is the status where the thread is eligible to run. In fact, the three States are combined into one. The common feature is that the thread is still active, but there are currently no conditions to run. In other words, it is runable, but if an event appears, it may return to the runable status. 5. Dead state: When the thread's run () method is completed, it is considered dead. This thread object may be active, but it is no longer a separate thread. Once a thread dies, it cannot be resumed. If the start () method is called on a dead thread, a java. lang. IllegalThreadStateException is thrown. For a detailed state transition diagram, see Figure 2 in my "Java multi-thread programming summary". To prevent thread execution from blocking the thread, consider the following three aspects without considering IO blocking: sleep; wait; blocked because an object is locked. 1. Sleep Thread. sleep (long millis) and Thread. sleep (long millis, int nanos) Static Method forces the currently executing thread to sleep (pause execution) to "slow down the thread ". When a thread sleeps, it falls asleep somewhere and does not return to a running state before waking up. When the sleep time expires, the system returns to the running status. Cause of thread sleep: the thread runs too fast or needs to be forced to enter the next round, because the Java specification does not guarantee reasonable rotation. Implementation of sleep: Call static methods. Try {Thread. sleep (123);} catch (InterruptedException e) {e. printStackTrace ();} Sleep position: to give other threads the opportunity to execute, you can set the Thread. sleep () is called within the thread run. In this way, the thread will be sleep during execution. For example, in the previous example, change a time-consuming operation to sleep to slow down the thread execution. This can be written as follows: public void run () {for (int I = 0; I <5; I ++) {// very time-consuming operation, used to slow down Thread execution // for (long k = 0; k <100000000; k ++); try {Thread. sleep (3);} catch (InterruptedException e) {e. printStackTrace ();.} system. out. println (this. getName () + ":" + I) ;}} running result: a 3: 0 LI 4: 0 A 3: 1 A 3: 2 A 3: 3 LI 4: 1 Li 4: 2 A 3: 4 Li Si: 3 Li Si: 4 Process finished with exit code 0. In this way, the thread will always sleep for 3 milliseconds during each execution, and other threads will have the opportunity to execute. Note: 1. Thread sleep is the best way to help all threads get running opportunities. 2. The thread automatically wakes up after its sleep ends and returns to the running status, not the running status. The time specified in sleep () is the shortest time that the thread does not run. Therefore, the sleep () method cannot guarantee that the thread starts to run after its sleep expires. 3. sleep () is a static method and can only control the currently running threads. The following is an example:/*** a counter that counts to 100 and pauses for 1 second between each number, output A string ** @ author leizhimin 9:53:49 */public class MyThread extends Thread {public void run () {for (int I = 0; I <100; I ++) {if (I) % 10 = 0) {System. out. println ("-------" + I);} System. out. print (I); try {Thread. sleep (1); System. out. print ("thread sleep for 1 ms! \ N ");} catch (InterruptedException e) {e. printStackTrace () ;}} public static void main (String [] args) {new MyThread (). start () ;}------- 0 0 thread sleep 1 millisecond! 1 thread sleeps 1 millisecond! 2 threads sleep for 1 ms! 3 threads sleep for 1 ms! 4 threads sleep for 1 ms! 5 threads sleep for 1 ms! 6 threads sleep for 1 ms! 7 threads sleep for 1 ms! 8 threads sleep for 1 ms! 9 threads sleep for 1 ms! ------- 10 10 threads sleep for 1 ms! 11 threads sleep for 1 ms! 12 threads sleep for 1 ms! 13 threads sleep for 1 ms! 14 threads sleep for 1 ms! 15 threads sleep for 1 ms! 16 threads sleep for 1 ms! 17 threads sleep for 1 ms! 18 threads sleep for 1 ms! 19 threads sleep for 1 ms! ------- 20 20 threads sleep for 1 ms! 21 threads sleep for 1 ms! 22 threads sleep for 1 ms! 23 threads sleep for 1 ms! 24 threads sleep for 1 ms! 25 threads sleep for 1 ms! 26 threads sleep for 1 ms! 27 threads sleep for 1 ms! 28 threads sleep for 1 ms! 29 threads sleep for 1 ms! ------- 30 30 threads sleep for 1 ms! 31 threads sleep for 1 ms! 32 threads sleep for 1 ms! 33 threads sleep for 1 ms! 34 threads sleep for 1 ms! 35 threads sleep for 1 ms! 36 threads sleep for 1 millisecond! 37 threads sleep for 1 ms! 38 threads sleep for 1 ms! 39 threads sleep for 1 ms! ------- 40 40 threads sleep for 1 ms! 41 threads sleep for 1 ms! 42 threads sleep for 1 ms! 43 threads sleep for 1 ms! 44 threads sleep for 1 ms! 45 threads sleep for 1 ms! 46 threads sleep for 1 ms! 47 threads sleep for 1 ms! 48 threads sleep for 1 ms! 49 threads sleep for 1 ms! ------- 50 50 threads sleep for 1 ms! 51 threads sleep for 1 ms! 52 threads sleep for 1 ms! 53 threads sleep for 1 ms! 54 threads sleep for 1 ms! 55 threads sleep for 1 ms! 56 threads sleep for 1 ms! 57 threads sleep for 1 ms! 58 threads sleep for 1 ms! 59 threads sleep for 1 ms! ------- 60 60 threads sleep for 1 ms! 61 threads sleep for 1 ms! 62 threads sleep for 1 ms! 63 threads sleep for 1 ms! 64 threads sleep for 1 ms! 65 threads sleep for 1 ms! 66 threads sleep for 1 ms! 67 threads sleep for 1 ms! 68 threads sleep for 1 ms! 69 threads sleep for 1 ms! ------- 70 threads sleep for 1 ms! Thread 71 sleeps in 1 ms! 72 threads sleep for 1 millisecond! 73 threads sleep for 1 ms! 74 threads sleep for 1 ms! 75 threads sleep for 1 ms! 76 threads sleep for 1 ms! 77 threads sleep for 1 ms! 78 threads sleep for 1 ms! 79 threads sleep for 1 ms! ------- 80 80 threads sleep for 1 ms! 81 threads sleep for 1 ms! 82 threads sleep for 1 ms! 83 threads sleep for 1 ms! 84 threads sleep for 1 ms! 85 threads sleep for 1 ms! 86 threads sleep for 1 ms! 87 threads sleep for 1 ms! 88 threads sleep for 1 ms! 89 threads sleep for 1 ms! ------- 90 90 threads sleep for 1 ms! 91 threads sleep for 1 ms! 92 threads sleep for 1 ms! 93 threads sleep for 1 ms! 94 threads sleep for 1 ms! 95 threads sleep for 1 ms! 96 threads sleep for 1 ms! 97 threads sleep for 1 ms! 98 threads sleep for 1 ms! 99 threads sleep for 1 ms! Process finished with exit code 0 2. Thread priority and Thread concession yield () Thread concession are achieved through Thread. yield. The yield () method is used to pause the currently executed thread object and execute other threads. To understand yield (), you must understand the concept of thread priority. The thread always has a priority. The priority ranges from 1 ~ Between 10. The JVM thread scheduler is a priority-based preemptive scheduling mechanism. In most cases, the priority of the currently running thread is greater than or equal to the priority of any thread in the thread pool. However, this is only the case in most cases. Note: When designing multi-threaded applications, do not rely on the thread priority. Because the thread scheduling priority operation is not guaranteed, the priority of the thread can only be used as a way to improve program efficiency, but ensure that the program does not rely on this operation. When all threads in the thread pool have the same priority, the JVM Implementation of the scheduler can freely select the thread it prefers. At this time, there are two possible operations for the Scheduler: one is to select a thread to run until it is blocked or the execution is complete. Second, time slice provides equal operation opportunities for each thread in the pool. Set the thread priority: the default priority of a thread is the priority of the execution thread that creates it. You can use setPriority (int newPriority) to change the priority of a thread. For example, Thread t = new MyThread (); t. setPriority (8); t. start (); Thread priority is 1 ~ A positive integer between 10. JVM never changes the priority of a thread. However ~ The value between 10 is not guaranteed. Some JVMs may not recognize 10 different values, but merge each of these priorities into less than 10 priorities, then, two or more priority threads may be mapped to one priority. The default Thread priority is 5. There are three constants in the Thread class. The Thread priority range is defined as the highest priority that a static int MAX_PRIORITY Thread can have. The lowest priority that a static int MIN_PRIORITY thread can have. The default priority that the static int NORM_PRIORITY assigns to the thread. 3. The Thread. yield () method Thread. yield () is used to pause the currently executed Thread object and execute other threads. What yield () should do is to bring the current running thread back to the runable state, so that other threads with the same priority can get the running opportunity. Therefore, yield () is used to enable proper rotation among threads with the same priority. However, in practice, yield () cannot be guaranteed to achieve the goal of concession, because the concession thread may be re-selected by the thread scheduler. Conclusion: yield () never leads the thread to the waiting/sleep/blocking status. In most cases, yield () will cause the thread to go from the running state to the runable state, but it may not work. 4. The non-static join () method of the join () method Thread allows A Thread B to "join" to the end of another Thread. Before Execution of A, B cannot work. For example, Thread t = new MyThread (); t. start (); t. join (); in addition, the join () method also has an overloaded version with time-out restrictions. For example, t. join (5000); enables the thread to wait for 5000 milliseconds. If the wait time is exceeded, the thread stops waiting and becomes runable. The result of joining join () to the thread stack is that the thread Stack has changed. Of course, these changes are instantaneous. The following is a summary of the current position. Three methods are introduced for the Thread to exit the running status: 1. Call the Thread. sleep (): the minimum number of milliseconds to sleep the current thread (although it may be interrupted before the specified time ). 2. Call Thread. yield (): too many things cannot be guaranteed, although it usually returns the current running Thread to the runability state, so that threads with the same priority have the opportunity to execute. 3. Call the join () method to ensure that the execution of the current thread is stopped until the threads added to the thread are completed. However, if the thread it joins does not survive, the current thread does not need to be stopped. In addition to the preceding three methods, the following special cases may cause the thread to exit the running state: 1. The thread's run () method is completed. 2. Call the wait () method on the object (not on the thread ). 3. The thread cannot get a lock on the object. It is trying to run the method code of the object. 4. The thread scheduler can decide to move the current running state to the runable state to give another thread a running opportunity without any reason.

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.