Multithreading (ii)

Source: Internet
Author: User
Tags thread class

One, thread state

1-New status (new):

When a thread object is established using the New keyword and the thread class or its subclasses, the thread object is in the new state. It keeps this state until the program start () this thread.

2-ready State (Runnable):

When the thread object calls the start () method, the thread enters the ready state. The ready state thread is in the ready queue, waiting for the thread scheduler in the JVM to dispatch.

3-Operating status (Running):

If the ready state thread gets the CPU resources, it can execute run (), at which point the thread is in the running state. A running thread is the most complex and can become a blocking state, a ready state, and a dead state.

4-blocking status (Blocked):

If a thread executes a method such as sleep, suspend (hangs), and so on, the thread will enter a blocking state from the running state after the resource is lost. You can re-enter the ready state after the sleep time has arrived or the device resource has been acquired. Can be divided into three kinds:

Wait for blocking: the thread in the running state executes the wait () method, which causes the thread to enter a wait-blocking state.

Synchronous blocking: The thread acquires a synchronized synchronization lock failure (because the synchronization lock is occupied by another thread).

Other blocking: When an I/O request is made by the calling thread's sleep () or join (), the thread enters the blocking state. When the sleep () state times out, the join () waits for the thread to terminate or time out, or the I/O process completes and the thread is re-entered in a ready state. sleep () does not release the held sync lock

5-Death status (Dead):

A running state thread completes a task or exits the run () method because of an exception, and the thread switches to the terminating state. The thread of the dead state can no longer execute

Thread state transition diagram:

          

Second, thread scheduling

Java thread scheduling is the core of Java multi-threading, and only good scheduling can give full play to the performance of the system and improve the execution efficiency of the program. However, no matter how programmers write schedules, they can only affect the order of thread execution to the maximum extent, but not the precise control .

Thread Priority: Threads in Java are prioritized, and high-priority threads get more running opportunities.

The precedence of threads in Java is expressed as integers, with a value range of 1-10

There are three static constants in the thread class:

static int max_priority

The highest priority a thread can have, with a value of 10.

static int min_priority

The lowest priority a thread can have, with a value of 1.

static int norm_priority

The default priority assigned to the thread, with a value of 5.

You can use the SetPriority and getpriority methods of the thread class to set and get the priority of a thread, respectively.

The priority of a thread has an inheritance relationship, such as the B thread created in a thread, then B will have the same priority as a.

  Note: Thread priorities do not guarantee the order in which threads are executed, but only high-priority threads are more important

Iii. General methods of induction1, Thread.Sleep (long Millis)--Thread sleep

The sleep method is a thread class that provides a static method, which means that the currently executing thread is always paused for a period of time and into a blocking state. Instead of invoking the instance object, the current thread will go to sleep instead of the thread object that called the method .

   when the time of sleep ends, the thread re-enters the ready state , and the ready state goes into the running state, which is controlled by the system, we cannot control it accurately, so if calling Thread.Sleep (1000) causes the thread to sleep for 1 seconds, the result may be greater than 1 seconds.

2, Thread. yield () --Thread concession

The yield () method is also the thread class that provides a static method, which also allows the currently executing thread to pause , yielding CPU resources to other threads. But unlike the sleep () method, it does not go into a blocking state , but goes into a ready state . The yield () method simply pauses the current thread, re-enters the ready thread pool , and lets the system's thread scheduler reschedule again, which is entirely possible: when a thread calls the yield () method, The thread scheduler may also dispatch it to re-enter into run state execution .

In fact, when a thread calls the yield () method to pause, the priority is the same as the current thread, or a thread with a higher priority than the current thread is more likely to get the chance to execute , of course, only possible, because we cannot precisely interfere with the CPU scheduler thread. Use the following:

classMyThread extends Thread { PublicMyThread (String name,intPro) {super (name);//set the name of the thread         This. setpriority (PRO);//setting the priority level} @Override Public voidrun () { for(inti =0; I < -; i++) {System. out. println ( This. GetName () +"Thread First"+ i +"times to execute! "); ifI5==0) Thread.yield(); }    }} Public classLifecyclethread { Public Static voidMain (string[] args) throws Interruptedexception {NewMyThread ("Low",1). Start (); NewMyThread ("Intermediate",5). Start (); NewMyThread ("Advanced",Ten). Start (); }}

The difference between the sleep () method and the yield () side is as follows:

①, sleep method pauses the current thread, it will go into a blocking state, only when the sleep time, will be transferred to the ready state. After the yield method is called, it is directly into the ready state, so it is possible to just enter the ready state and be dispatched to the running state.

The ②, sleep method declaration throws a interruptedexception, so the sleep method is called to catch the exception, or the display declares that the exception is thrown. The yield method does not declare a thrown task exception.

The ③ and sleep methods are more portable than the yield method, and generally do not rely on the yield method to control the execution of concurrent threads.

Sleep () causes the current thread to stall, so the thread that executes sleep () is definitely not executed for the specified time, and yield () simply returns the current thread back to the executable state, so the thread that executes yield () is likely to be executed immediately after entering the executable state.

The sleep method makes the current running thread sleepy for a period of time, into a non-operational state, the length of time is set by the program, the yield method makes the current thread out of the CPU possession, but the time is not set.

In fact, the yield () method corresponds to the following actions: first detect whether the thread with the same priority is in the same operational state, and if so, hand over the CPU's possession to this thread, or continue running the original thread. So the yield () method is called "concession,"which gives the opportunity to other threads of equal priority.

In addition, the sleep method allows a lower-priority thread to get a run-time, but when the yield () method executes, the current thread is still in a running state, so it is not possible to get CPU possession when a lower-priority thread is given. In a running system, if a higher-priority thread does not call the sleep method and is not blocked by i\o, the lower-priority thread can only wait for all higher-priority threads to run to the end before the opportunity runs.

  3. join--wait for thread to terminate

 It is not a static method , and the application scenario is when a thread must wait for another thread to execute before it executes, the thread class provides a join method to accomplish this function.

  Why use the Join () method?

In many cases, the main thread is generating and starting a child thread, and if a lot of time-consuming operations are to be performed in the sub-thread, the main thread will often end up before the child thread, but if the main thread finishes processing the other transactions, it needs to use the result of the child thread, that is, the main thread needs to wait for the child The join () method will be used at this time.

Do not add the join code as follows:

classMyThread extends Thread { PublicMyThread (String name,intPro) {super (name);//set the name of the thread         This. setpriority (PRO);//setting the priority level} @Override Public voidrun () { for(inti =0; I <Ten; i++) {System. out. println ( This. GetName () +"Section"+ i +"times to execute! "); }    }} Public classLifecyclethread { Public Static voidMain (string[] args) throws Interruptedexception {System. out. println ("Main thread Start"); MyThread T1=NewMyThread ("Child Threads",Ten);        T1.start ();  for(inti =0; I <Ten; i++) {System. out. println ("main thread Execution code"); } System. out. println ("Main thread End"); }}
The child thread executes the 1th time! The child thread executes the 2nd time! The child thread executes the 3rd time! The main thread ends the 4th time that the child threads execute! The child thread executes the 5th time! The child thread executes the 6th time! The child thread executes the 7th time! The child thread executes the 8th time! The child thread executes the 9th time!
Output Results

 This output is only one of the cases where the main thread execution does not wait for a child thread.

  Add the join code as follows:

classMyThread extends Thread { PublicMyThread (String name,intPro) {super (name);//set the name of the thread         This. setpriority (PRO);//setting the priority level} @Override Public voidrun () { for(inti =0; I <Ten; i++) {System. out. println ( This. GetName () +"Section"+ i +"times to execute! "); }    }} Public classLifecyclethread { Public Static voidMain (string[] args) throws Interruptedexception {System. out. println ("Main thread Start"); MyThread T1=NewMyThread ("Child Threads",Ten);       T1.start ();        T1.join ();  for(inti =0; I <Ten; i++) {System. out. println ("main thread Execution code"); } System. out. println ("Main thread End"); }}
The main thread starts a sub-thread execution for the No. 0 time! The child thread executes the 1th time! The child thread executes the 2nd time! The child thread executes the 3rd time! The child thread executes the 4th time! The child thread executes the 5th time! The child thread executes the 6th time! The child thread executes the 7th time! The child thread executes the 8th time! The child thread executes the 9th time! Main thread execution code main thread execution code main thread execution code main thread execution code main thread execution code main thread execution code main thread execution code main thread execution code main thread execution code main thread execution code thread end
Output Results

 The main thread must wait until the child threads are finished.

  

4, interrupt ()

  It simply sends an interrupt signal to the thread , allowing the thread to throw in an infinite wait, such as a deadlock, to end the thread, but if you eat the exception, the thread will not break!

5, Some common methods of threading class:  

  Sleep (): Forces a thread to sleep n milliseconds.
IsAlive (): Determines whether a thread is alive.
Join (): Waits for the thread to terminate.
Activecount (): The number of active threads in the program.
Enumerate (): Enumerates the threads in the program.
CurrentThread (): Gets the current thread.
Isdaemon (): Whether a thread is a daemon thread.
Setdaemon (): Sets a thread as the daemon thread. (The difference between a user thread and a daemon thread is whether to wait for the main thread to end up relying on the main thread end)
SetName (): Sets a name for the thread.
Wait (): Forces a thread to wait.
Notify (): Notifies a thread to continue running.
SetPriority (): Sets the priority of a thread.

Iv. timing of multi-threaded use

  The purpose of multithreading is to allow the program to execute concurrently, change the original serial execution mode, to improve efficiency, when the program has two subsystems need to execute concurrently, you need to use multithreading .

Multithreading is the ability to write high-efficiency programs, but it is important to note that too many threads can actually reduce the execution efficiency of the program, because the switch between threads is also a CPU resource overhead, too many threads will make the CPU in the context (between threads) switch time is greater than the time the program executes.

Multithreading (ii)

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.