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

Source: Internet
Author: User

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

We have learned the basics of threads, how to create multithreading, And the thread lifecycle. With existing knowledge, we can write simple programs that use multithreading to process a large number of tasks. However, when the application scenario is complex, we also need to start with management control to better manipulate multithreading. As we mentioned in section 1, one of the advantages of Multithreading is that we can better manage and control multithreading through coding and existing class libraries. Next, I will introduce in detail how to manage multithreading, including waiting for threads, daemon threads, sleep of threads, sudden stop of threads, concession of threads, and priority of threads. This section describes the first two parts: Waiting For threads and daemon threads.

1. Thread waiting

We often cut the same thing, divide it into multiple things, and then open up multiple threads for processing (a bit of governance flavor ). After processing multiple tasks, we need to handle them in a unified manner. This is a bit boring: for example, if we want to export a file, the number of lines in the file is very large, which is about several hundred million lines of data. You can export data directly, which may cause the system to get stuck. Otherwise, it may time out. What should we do at this time? We can divide the data into several parts. For example, each five thousand pieces of data is a copy of data and then exported to the file using a thread. This will generate several copies of the file. After all the files are exported, We can summarize the data. But there is a problem here: When will all threads have imported data? We cannot always check whether the file exists one by one.

Here java provides us with a special method for waiting for Join (). when a thread executes the join () method of another thread, the current thread will be blocked until the execution of other threads ends.

See the following code:

1 public class newThread extends Thread 2 {3 public newThread (String name) 4 {5 super (name); 6} 7 public void run () 8 {9 int I = 100; 10 while (I --> 0) 11 {12 sleep (100); 13} 14} 15 16 public static void main (String args) throws Exception17 {18 Thread son_1 = new newThread ("thread-1"); 19 Thread son_2 = new newThread ("thread-2"); 20 son_1.start (); 21 son_2.start (); 22 son_1.join (); // note here 23 son_2.join (); 24 System. out. println ("all threads is over") 25} 26}

 

We start thread 1 and thread 2 respectively. These two threads will run separately and will not affect each other. Then we will use the main thread to wait for thread 1 until it ends and we will start waiting for thread 2. If thread 1 is longer than thread 2, then after we wait for thread 1, thread 2 does not need to wait and output the result directly.
The join method has three forms of overloading.

1 join () 2 join (long millis) // 3 join (long millis, int nanos) // millis millisecond nanos microsecond

The first method continues to run downward until the thread ends. The second and third methods are waiting within a limited period of time. If the time ends, the second and third methods will not continue to wait (which can be used for timeout determination ), note that the third method is not commonly used. This is mainly because it is difficult for java and hardware to control time in microseconds, so it is not very accurate to control.

2. daemon thread

Daemon Thread is also called an elf Thread and a background Thread. At first glance, the word "daemon" seems to be very powerful, as if it is protecting other threads. In fact, it is very simple and not so mysterious. All languages are designed for easier use.

Imagine such a scenario: in one test room, the candidates are all immersed in answers. Apart from the candidates and invigilators, they are responsible for maintaining order in the test room, help candidates with difficulties. When all the candidates submit the exam (or after the time is reached, the examinee is forced to submit the exam (the end thread), The invigilator's obligations have been fulfilled and do not need to continue running. In short, this invigilator provides background services for other students. When all the candidates have been suspended, the obligations of the instructors have been completed and they can exit.

Some people may think that this is not simple. We just need to wait for the teacher to wait for all the students to finish, just like a thread ?! This answer is not correct either. Yes, the teacher's thread is indeed waiting for the student thread to end. What's wrong is that the teacher thread is waiting and still providing services. It's not as easy as reading the book after all the students stop writing. In Jvm, there is a thread GC that all developers are familiar with. It provides services silently while other threads are running. When other threads are finished, they exit silently.

The following code

1 public class newThread extends Thread 2 {3 public newThread (String name) 4 {5 super (name); 6} 7 public void run () 8 {9 int I = 100; 10 while (I --> 0) 11 {12 sleep (100); 13} 14} 15 16 public static void main (String args) throws Exception17 {18 Thread son_1 = new newThread ("thread-1"); 19 Thread son_2 = new newThread ("thread-2 "); 20 Thread daemonThread = new newThread ("thread-daemonThread"); 21 son_1.start (); 22 son_2.start (); 23 24 daemonThread. setDaemon (true); // pay attention to the 25 daemonThread. start (); 26 son_1.join (); 27 son_2.join (); 28 System. out. println ("all son_threads is over") 29} 30} 31 32 class DaemonThread33 {34 public DaemonThread (String name) 35 {36 super (name ); 37} 38 public void run () 39 {40 int I = 1000; 41 while (I --> 0) 42 {43 sleep (100); 44} 45} 46}

In the code, the Daemonthread thread is set to a background thread. When the main thread waits for the completion of the subthread, The Daemonthread thread also ends and does not continue to run. We can set a thread in this way to maintain the normal operation of other threads, such as background counting, timing, and querying whether each client is online (Heartbeat) and pushing events.
Java also provides the IsDaemon () method to determine whether the thread is a background thread.

Note thatIf you want to set a thread as a background thread, you must set it before the thread starts "ready" (start (). Otherwise, an invalid thread state exception occurs.

 

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.