Java Multithreaded Development Series four: Topsy-Threading (threading control 1)

Source: Internet
Author: User

In the previous article we have learned: the basic situation of threads, how to create multithreading, the life cycle of threads. With the knowledge we have, we can already write a simple program that uses multithreading to handle a large number of tasks. However, when the application scenario is complex, we also need to start with the management control, to better manipulate multithreading. In the first section we have said that one of the benefits of using multithreading is that we can better manage and control multithreading through coding and existing class libraries. Next I'll describe in detail how to manage multiple threads, including: Waiting on threads, daemon threads, sleep on threads, abrupt stopping of threads, concession of threads, priority of threads, etc. Because of the more content, this section first describes the first two parts: the wait on the thread, the daemon thread

1, the thread waits

We often cut the same thing and divide it into smaller pieces, and then open up multiple threads to deal with (a bit of the taste of division). We need to deal with it once more is done. This is a bit boring: for example, we want to export a file, the number of rows of this file is very much about hundreds of thousands of rows of data. Direct export can also cause the system to card a bit, a serious point may be timed out. What happens now? We can divide into several parts, such as every 5,000 pieces of data is a piece of data, and then use a thread to export to the file, so that a number of files will be generated. When all the files are exported, we'll summarize the data and we'll be OK. But here's a question: When are all the threads going to finish the data? We can't just check for the existence of a file.

Here Java provides us with a dedicated method for waiting join (). When a thread executes the join () method of another thread, the current thread blocks until the other thread finishes executing.

such as the following code:

1  Public classNewthreadextendsThread2 {3      PublicNewthread (String name)4     {5         Super(name);6     }7      Public voidRun ()8     {9        inti=100;Ten         while(i-->0) One        { ASleep (100); -        } -     } the      -      Public Static voidMain (String args)throwsException -     { -Thread son_1=NewNewthread ("Thread-1"); +Thread son_2=NewNewthread ("Thread-2"); - Son_1.start (); + Son_2.start (); ASon_1.join ();//Watch this . at Son_2.join (); -System.out.println ("All threads are over") -     } -}

We started thread 1 and thread 2 respectively. The two lines routines each other and do not affect each other, and then we use the main thread to wait for thread 1 until it ends, and we start waiting for thread 2. If thread 1 is longer than thread 2, then after we wait for thread 1, thread 2 will not have to wait and output the result directly.
There are three types of overloads in the Join method

1 Join () 2 Join (long Millis)//3 Join (long millis,int Nanos)// Millis Ms   Nanos μs

The first method continues down until the waiting thread ends, and the second and third methods wait within a limited time, and if the end of time does not continue to wait (which can be used for time-outs), note that the third method is not commonly used, mainly because Java and hardware control of time is difficult to pinpoint to microsecond level, So it is not very accurate to control.

2. Daemon Thread

The daemon thread (Daemon thread) is also known as the Sprite, background thread. At first listen to guard the word, feel like very strong meaning, like in the protection of other threads of thread, actually very simple, and not so Xuan. All language designs are designed for more convenient use.

Imagine such a scenario: in an examination room, candidates are immersed in the answer, in addition to candidates, as well as the supervisor, his role is to maintain the order of the examination rooms, for the candidates with difficulties to help. When all the candidates are handed in (or when the time is up, the examinee is forced to put it in (end thread)), the supervisor's obligation has been completed without the need to continue running. In short, this supervisor is for other students to provide back-office services, when all the candidates have stopped the pen, the teacher's obligations have ended, you can exit.

Some people see here, may feel that this is not simple, we just like the thread waiting for the teacher to wait for all the students to end, not just?! The answer is neither right nor wrong. The right is that the teacher's thread is really waiting for the student thread to end, and the wrong place is that the teacher thread is waiting for the service, and not all the students are so easy to collect after the pen stops. In the JVM, there is a thread GC that all developers are familiar with, and it is a silent service while other threads are running, and silently exits when the other threads end.

The following code

1  Public classNewthreadextendsThread2 {3      PublicNewthread (String name)4     {5         Super(name);6     }7      Public voidRun ()8     {9        inti=100;Ten         while(i-->0) One        { ASleep (100); -        } -     } the      -      Public Static voidMain (String args)throwsException -     { -Thread son_1=NewNewthread ("Thread-1"); +Thread son_2=NewNewthread ("Thread-2"); -Thread daemonthread=NewNewthread ("Thread-daemonthread"); + Son_1.start (); A Son_2.start (); at          -Daemonthread.setdaemon (true);//Watch this . - Daemonthread.start (); - Son_1.join (); - Son_2.join (); -System.out.println ("All son_threads are over") in     } - } to  + classDaemonthread - { the      PublicDaemonthread (String name) *     { $         Super(name);Panax Notoginseng     } -      Public voidRun () the     { +        inti=1000; A         while(i-->0) the        { +Sleep (100); -        } $     } $}

In code where the Daemonthread thread is set to a background thread, the daemonthread thread ends and does not continue to run when the main thread waits for the child thread to end. We can set up a thread in this way, specifically to maintain the normal operation of other threads, such as background counting, timing, querying whether each client remains online (heartbeat), push events, etc.
Java also provides a Isdaemon () method to determine whether this thread is a background thread.

One thing to note here is that if you want to set a thread as a background thread, you must set it when the thread is not ready to start (Start ()), or an illegal thread state exception will be thrown

Java Multithreaded Development Series four: Topsy-Threading (threading control 1)

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.