Java Concurrency: Thread class Depth parsing __java

Source: Internet
Author: User
Tags thread class

Java Concurrency: Thread class Depth resolution

Summary:

The various operations of the thread class in Java are inextricably linked to the lifecycle of threads, and understanding the lifecycle of threads helps to understand the methods in the thread class. In general, threads are created, ready, run, blocked, and extinct in five states, from initial creation to eventual extinction. In the lifecycle of a thread, context switching enables it to resume execution from a breakpoint by storing and restoring the CPU state. Combined with thread lifecycle, this article introduces the common API of thread at last. In particular, I will pay special attention to two issues when introducing relevant APIs that cause threads to enter the waiting state, including the timed waiting state:

If the client invokes the API, it releases the lock (if it has a lock at this point);

If the client invokes the API, it will hand over the CPU (typically, the thread will hand over the CPU when it enters the waiting state (including the timed waiting state); Thread lifecycle

The specific operation of the thread class in Java is inextricably linked to the life cycle of the thread, and understanding the lifecycle of the thread helps to understand the methods in the thread class.

In a Java virtual machine, threads go through several states: Creation (new), Ready (Runnable/start), running (running), blocking (blocked), Waiting (Waiting), Waiting (time), from the initial creation to the final extinction. Waiting) and Extinction (dead/terminated). At a given point in time, a thread can only be in one state, and the meaning of each state is shown in the following illustration:

            

When we need a thread to perform a child task, we must first create a thread. However, after the thread is created, it will not immediately enter the ready state, because the running of the thread requires some conditions (such as program counter, Java stack, local method stack, etc.), only the thread running all the necessary conditions are satisfied to enter the ready state. When the thread is in a ready state, it does not mean that the CPU execution time is immediately available, and perhaps the CPU is performing something else at this time, so it waits. When the CPU execution time is obtained, the thread actually enters the running state. Thread in the running state, there may be several reasons for the current thread does not continue to run, such as the user actively let the thread sleep (after a certain amount of time to sleep after the execution), the user actively let the thread wait, or blocked by the synchronized block, the corresponding multiple states: time Waiting (sleep or wait a certain time), waiting (waiting to be awakened), blocked (blocking). When a sudden interruption or a subtask completes, the thread will die out.

In fact, Java defines only six thread states, namely New, Runnable, waiting,timed waiting, Blocked, and terminated. To express the state of the thread between creation and extinction, the following figure divides the runnable state into two states: The running state and the Ready state:

              two. Context switching

Take a single core CPU as an example, the CPU can only run one thread at a time. In the process of running a thread, the CPU instead runs another thread, which is called a thread context switch (similar to a process).

Because it is possible that the task of the thread is not finished, you need to save the running state of the threads during the switch so that the next time you switch back, you can continue to run the previous state. For example, a thread A is reading the contents of a file, reading half of the file, pausing thread A, going to execute thread B, and when switching back to executing thread A, we do not want thread A to read from the beginning of the file.

So you need to record the running state of thread A, so what data is logged. Because the next time you recover, you need to know which instruction the current thread has executed before. So you need to record the value of the program counter, in addition to the thread is in the calculation of the time is suspended, so the next time to continue the execution of the time required to know the value of the variable before the number, so you need to record the state of the CPU registers. Therefore, in general, the thread context switching process will record the program counter, CPU register state and other data.

In essence, a thread's context switch is the process of storing and recovering a CPU state, which enables thread execution to recover from a breakpoint, which is supported by a program counter.

Although multithreading can improve the efficiency of task execution, you should pay attention to these factors when multithreaded programming due to the same overhead costs associated with thread switching, and multiple threads that can lead to increased system resource consumption. three. Creation of Threads

In Java, there are generally two ways to create a thread to perform subtasks: inheriting the thread class and implementing the Runnable interface. The thread class itself implements the Runnable interface, and the biggest limitation of creating threads using the inherited thread class is that it does not support multiple inheritance. In particular, two points should be noted, and multithreading must override the Run () method, which defines the tasks to be performed in the run () method;

The run () method does not require a user to invoke.

              

code sample created by thread:

public class ThreadTest {public static void main (string[] args) {//Create threads new Thread () using the inherited thread class () {
            @Override public void Run () {System.out.println ("Thread");

        }}.start (); Creating thread thread threads with the implementation of the Runnable interface = new Thread (new Runnable () {@Override public void
            Run () {System.out.println ("Runnable");
        }
        });

        Thread.Start ();
    The main thread main System.out.println ("main") created by the JVM;
    
    }/* output: (The code's run results are independent of the code's execution order or call order) Thread main Runnable *///:~ 1 2
    
    3 4 5 6 7 8 9 10 11 12 
    
    13 14 15 16 17 18 19 20 21 22 23
   
    24 25 26 27 28

After you have created your own thread class, you can create the thread object and then start the thread through the start () method. Note that the run () method simply defines the task that needs to be performed and does not require a user to invoke it. After starting a thread through the start () method, if the thread obtains CPU execution time, it enters the run () method body to perform the specific task. If the user calls the run () method directly, which is equivalent to executing the run () method in the main thread, there is no difference from the normal method call, and a new thread is not created to perform the defined task at this time. In effect, the start () method informs the thread planner that the thread is ready to allow the system to schedule a time to call its run () method, which is to get the thread running. The run () method in the Thread class is defined as:

    /* What'll be run. *
    private Runnable target;  Class Thread member

    /**
     * If This Thread is constructed using a separate <code>Runnable</code> run object , 
     * Then that <code>Runnable</code> object ' s <code>run</code> the is called; otherwise,< C6/>* This method does the nothing and returns. 
     * 
     * Subclasses of <code>Thread</code> should override this method. 
     * */public
    void Run () {
        if (target!= null) {
            target.run ();
        }
    }
   
   
    
    1
    
    2
    
    3
    
    4
    
    5
    
    6 7 8 9 (15)
    
    16
   
   
Four. Thread class detailed

The thread class implements the Runnable interface, and in the thread class, there are some of the more critical attributes, such as name, the thread name, which can be specified by the parameters in the constructor of the thread class. Priority represents the priority of a thread (the maximum is 10, the minimum value is 1, the default is 5), and daemon indicates whether the thread is a daemon, and target represents the task to perform.

            

1. Methods related to thread running state

1) Start method

Start () is used to start a thread, and when the method is invoked, the corresponding thread enters the ready state, and the Run () method in the thread is invoked at some time.

2) Run method

The run () method is not required to be invoked by the user. When a thread is started with the start () method, once the thread obtains the CPU execution time, it enters the run () method body to perform the specific task. Note that when you create a thread, you must override the run () method to define the specific task to perform.



In general, there are two ways to achieve the effect of overriding the Run () method:

Direct rewrite: Directly inherit the thread class and rewrite the run () method;

Indirect overrides: Passing the Runnable object through the thread constructor (note that the Runnable object's run () method is actually rewritten).

3) Sleep method

Method Sleep () is used to get the currently executing thread (the thread returned by the CurrentThread () method) asleep in the specified number of milliseconds, and hand over the CPU to perform other tasks. When a thread sleeps, it does not necessarily occur immediately because the CPU may be performing other tasks at this time. So, calling the sleep method is equivalent to getting the thread into a blocking state. The method has the following two characteristics:

If you call the Sleep method, you must catch the interruptedexception exception or throw the exception to the upper level;

The Sleep method does not release the lock, which means that if the current thread holds a lock on an object, other threads cannot access the object even if the sleep method is invoked.

           

4) Yield method

Invoking the yield () method allows the current thread to hand over the CPU resources to allow the CPU to execute other threads. However, yield () can not control the specific time to hand over the CPU. It is to be noted that

The yield () method allows only threads with the same priority to have the opportunity to get CPU execution time;

Calling the yield () method does not leave the thread in the blocking state, but rather the thread is back in the ready state, and it only needs to wait for the CPU to be executed again;

It also does not release locks.


   

public class Mythread extends Thread {

    @Override
    
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.