Java multi-thread Development Series 4: Playing with multiple threads (thread control 2), java multi-thread

Source: Internet
Author: User
Tags thread stop

Java multi-thread Development Series 4: Playing with multiple threads (thread control 2), java multi-thread

In the thread control section above (click here for details), we have explained the thread waiting for join () and daemon threads. This section describes the remaining thread control content, including thread sleep, concession, priority, suspension, recovery, and stop.

Let's go straight to the question:

3. Thread sleep ()

This method is basically useful in all the learning cases that introduce multithreading development. This method means sleep (true, please believe me ...). Well, if you think it is not specific enough, you can think it is to pause the current thread and the current thread will enter the blocking state. When the sleep time ends, the current thread will enter the ready state again, start a new round of preemption plan!

So what are the purposes of this method in actual development? For example, in many cases, the current thread does not need to monitor or run in real time, but regularly checks whether a certain status is up to standard. If it meets the starting conditions, so do something, otherwise you will continue to sleep. For example, in heartbeat mode, we will send a daemon thread to send data requests to the server. When a response is received, We will sleep for a while. After waking up again, we continue to send such requests. Examples in real life: for example, if we are waiting for a TV to start broadcasting, but we don't want to watch the previous advertisement, we may wait for a while to switch the TV channel to the position to be played, if an advertisement is still being played, we will jump to another channel to watch it, and regularly switch to the target channel to view it.

The Code is as follows:

1 public class ThreadStudy 2 {3 public static main (String [] arg) throws Exception 4 {5 for (int I = 0; I <= 1000; I ++) 6 {7 if (IsInternetAccess () 8 {9 Thread. sleep (1000*6); // note here 10} 11 else12 {13 System. out. println ("Error! Can not Access the Internet! ") 14 break; 15} 16} 17} 18 private Boolean IsInternetAccess () 19 {20 // bala bala21 return true; 22} 23}

 

The code indicates checking whether the network is smooth. If the network is smooth, the system goes to sleep and wakes up again after 6 seconds of sleep. By sleep the thread, we can effectively allocate resources so that other threads can get cpu resources faster during idle hours. One thing to note here is that after the thread goes to sleep, it enters the blocking state (whether or not the cpu is idle or not, it will still be paused, which is mandatory). When the sleep time ends, the system enters the ready state. You need to compete again to seize the cpu permission, instead of immediately executing the method after sleep. Therefore, the actual interval is greater than or equal to the sleep time.

The java Thread class provides two static methods to pause a Thread.

1  static void sleep(long millis)  2 3  static void sleep(long millis,int nanos)

Millis is millisecond and nanos is microsecond. Similar to thread join (), due to jvm and hardware, we only use method 1.

4. Thread concession yield ()

In our daily life, we all met such an example. We made a quiet handsome man (or female man) on a bus or subway. At this time, we came in with an old man or pregnant woman, you stood up silently and gave your seat to the old man. Wait for a new free seat. Or you play a computer game silently, and then your mother shouted your full name (yes, it is the full name). At this time, your first reaction was, I did something wrong, the second reaction is to put down the mouse in your hand and run to your mom to accept the reprimand. All of this is because the thread being processed is put on hold and we (cpu) process the current emergency transaction. In software development, there are similar scenarios. For example, if a thread processes a large number of tasks and other threads are unable to seize resources, we must make concessions on our own initiative at this time, give other threads a fair opportunity to seize.

Add an image from the Internet: When we are strong, we should give the weak a chance. Back to question.

Below is the code

 

1 public class TestThread extends Thead 2 {3 public testThread (String name) 4 {5 super (name); 6} 7 8 public void run () 9 {10 for (int I = 0; I <= 1000000; ii ++) 11 {12 send ("MsgBody"); 13 if (I % 100 = 0) 14 {15 Thread. yield (); // note here 16} 17} 18} 19 20 public static void main (String [] args) throws Exception21 {22 TestThread thread1 = new TestThread ("thread1"); 23 thread1.setPriority (Thread. MAX_PRIORITY); // Note: here 24 25 TestThread thread2 = new TestThread ("thread2"); 26 thread1.setPriority (Thread. MIN_PRIORITY); // Note: HERE 27 thread1.start (); 28 thread2.start (); 29} 30}

After we start the thread, when the thread sends one hundred messages each time, we pause the current thread to bring the current thread into the ready state. In this case, the CPU recalculates the priority once again and starts if the priority is higher.
The sleep method and yield () method are compared here.

(1) After the sleep method suspends a thread, the thread will enter the blocking state (even for an instant). At this moment, the cpu will only select the thread in the ready state, therefore, the thread that is currently sleeping is not selected. (Even if there are no other available threads ). The yield () method enables the current thread to enter the ready state immediately. The optional thread range selected by the cpu contains the thread that is currently executing the yield () method. If there are no other threadsPriorityIf the thread is higher than (or equal to) yield (), the cpu will still select the original yield () thread to restart.

(2) The sleep method throws an InterruptedException exception. Therefore, calling the sleep method requires declaring or capturing this exception (which is troublesome for C # To handle exceptions), while yield does not declare that an exception is thrown.

(3) The sleep method has good portability and can correspond to the underlying methods of many platforms. Therefore, the place where sleep () is used must be redundant;

(4) After sleep suspends a thread, the thread will sleep for a certain period of time before it changes to the ready state. If it is defined as sleep (0), the blocking state is set to 0, immediately enters the ready state. This usage is basically the same as that of yield (): it is to make a new choice for the cpu, so as to avoid overoccupying the cpu due to the current thread, the program is suspended.

The biggest difference between the two methods is that sleep throws an exception and needs to handle it. yield () does not. The minor differences between the two methods are also different in jdk versions, let's take a look at this question on stackoverflow: Are Thread. sleep (0) and Thread. yield () statements equivalent? (Click here to enter)

5. thread priority setting

The priority of a thread is equivalent to the weight of an opportunity. When the priority is high, the higher the chance of obtaining an execution opportunity, and the lower the chance of obtaining an execution opportunity. (Remember, the higher or smaller the possibility ).

In the thread concession section of this section, we have used code to demonstrate how to set the thread priority. Here, no special code is displayed. (Anti-theft connection: This article first from the http://www.cnblogs.com/jilodream)

Thread provides two methods for us to set and obtain the Thread priority respectively.

  

1 setPriority(int newPriority)2 getPriority()

SetPriority is the set priority. The value range of the parameter is 1 ~ Before 10.

Three static constants are also set:
Tread. MAX_PRIORITY = 10;

Tread. NORM_PRIORITY = 5;

Tread. MIN_PRIORITY = 1;

Although java provides 10 priorities for threads, the priority of underlying platform threads is usually not 10, which leads to the relationship between the two. (For example, the OS has only five priorities, so that each of the two priorities corresponds to only one OS priority ). In this case, we usually only use these three static constants to set the priority, instead of specifying the specific priority value in detail (because multiple priorities may correspond to a certain priority of the OS ), this causes unnecessary trouble.

In addition, the default priority of each thread is the same as that of the parent process created for it. By default, the priority of the Main thread is normal, so the new thread created by the above Code is also normal by default.

The following are the key concepts of priority:

In fact, the priority you set does not really represent the priority of the thread or startup. This is only a reference indicator for calculating the priority when the OS starts the thread. The OS also checks whether the current thread occupies the cpu for a long time. If so, the OS appropriately increases the priority of other "Hunger" threads. Threads that occupy cpu for a long time are forcibly suspended. This setting can only increase the chance that the thread will be executed to some extent. In fact, the threads that occupy the cpu for a long time are not a single occupy for a long time, but are selected consecutively, which leads to the illusion of long-term occupation.

So after setting the priority,The real execution sequence of threads is not predictable or even confusing.. After understanding this, we are developing and controlling multithreading, and we cannot expect to simply set the priority to arrange the thread execution sequence.

Two articles are referenced here. For more details, refer to the original article:

(1) Java multithreading -- thread priority (original link)

(2) Meaning of Thread. sleep (0) (original article)

 

6. Force end thread Stop ()

Sometimes we will find that some running threads do not need to be executed any more, but there is still some time before the end of multithreading. In this case, we need to force the end of multithreading. Java once provided a Stop () method specifically used to end the thread, but this method has been discarded and is not recommended to developers.

This is because this method is inherently insecure. End the Thread with Thread. stop, and jvm will force release all the objects it locks. When the object state is inconsistent at a certain time point (in the process of processing the transaction), if the object is forcibly released, it may lead to many unexpected consequences. Specifically, the system generates a ThreadDeath exception at the top of the stack of the locked resource. This unchecked Exception will silently close related threads. In this case, the data in the object may be inconsistent, and the user will not receive any alarms for inconsistent objects. The consequences of this inconsistency will only be discovered during future use, and unexpected consequences have been generated.

Some may consider calling the Stop method and then capturing the ThreadDeath form to avoid this form. This kind of idea seems to be feasible. In fact, the ThreadDeath exception may be thrown at any location, which requires careful consideration. Even if the exception is captured and handled, the system may throw a new ThreadDeath. Therefore, we should stop this method at the source, instead of continuously patching to fix it.

The problem arises. What should we do if we really want to close a thread?

Through the Stop method, we can understand that it is often difficult to close the thread outside the thread to handle data consistency and internal running processes of the thread. Then, we can determine whether to continue running by setting the persistent flag variable, and then the thread regularly checks whether the variable is the end identifier.

For example, I have written a thread that monitors computer indicators. This thread regularly checks the status variables in the cache. This status cache can be set externally. When the thread finds that this variable has been set to "end", it will process the remaining work internally and directly Run the Run method.

 

7. Thread suspension and restoration suspend () and resume ()

We sometimes need to suspend the thread, but the specific suspension time is not clear, it is only possible to notify this thread to start working under a certain condition in the future. Java provides two methods specifically for us:

Suspend ()/resume.

Through the title, we already know that these two methods are not recommended by java, but why?

Suspend directly suspends the current thread and causes it to enter the blocking state, but does not modify the resources it internally controls and locks (similar to the stop method, it is often difficult to view the internal running status and control resources outside the thread, so it is difficult to handle ). In this way, the resources locked by the suspended thread can no longer be accessed by other resources, resulting in a false lock. Other threads can re-access resources only after the thread is recovered and the resources in the thread are released. However, if other threads are suspended in the resume process) the thread line, You need to first access the locked resources, this will form a real lock.

The problem arises. What should we do if we really want to suspend a thread?

Similarly to stop (), we can set an identifier inside the thread that may be suspended to indicate whether the thread is being suspended. If the variable indicates that the thread is being suspended, use wait () command to let it enter the waiting state. If the identifier indicates that the thread can be recovered, use notify () to wake up the thread again. (I will explain these two methods in later thread communication ).

Two articles are referenced here. For more details, refer to the original article:

(1) Why do you not approve of using Thread. stopsuspend and resume () (original link)

(2) insecure java stop method (original link)

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.