[Multi-threading] (3) java.lang.Thread summary

I. Introduction

        The first step of learning multi-threading has already been introduced. Regarding processes and threads, it is a conceptual thing, so the second step must be a practical "Hello World" practice. The final core method of Thread class, I do A picture is drawn as follows:

   

       I have made a summary of the most commonly used methods of the Thread class, as shown above, the basic concepts in the foundation. As for each specific method, you need to think about it and put it into practice before you can use it freely. I recommend the book "Core Technology of Java Multithreaded Programming". I only make a macro summary, and I will not repeat the creation of wheels for details. .


2. Basics

       After the basic Thread common methods can be used proficiently, briefly introduce the java.lang.Thread class in jdk:

       1.https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#field_summary  

       2.https://docs.oracle.com/javase/7/docs/api/java/lang/Runnable.html 

       As above, it is Oracle's official document introduction to the Thread class and the Runnable interface (the Thread class implements the Runnable interface)


       Among them, several Thread related classes under the java.lang package are as follows:

        

     (The usage of "ThreadLocal", "ThreadDeath", and "ThreadGroup" will be introduced separately after this series of blogs)


      一、Runnable Interface

      Since the Thread class inherits from the Runnable interface, refer to the Runnable interface documentation:

     (0) Originated from jdk 1.0

     (1) All Known Subinterfaces: (sub interface)

       RunnableFuture<V>, RunnableScheduledFuture<V>

     (2) All Known Implementing Classes: (implementation classes in jdk)

      AsyncBoxView.ChildState, ForkJoinWorkerThread, FutureTask, RenderableImageProducer, SwingWorker, Thread, TimerTask

     (3) There is only one method!

//When an object implementing interface Runnable is used to create a thread, starting the thread causes the object's run method to be called in that separately executing thread.
//The general contract of the method run is that it may take any action whatsoever.
void run()
      After reading the source code, I found that start() makes the thread start to queue up in the CPU to prepare for execution, and the method run(), which actually runs the thread, is actually defined in the Runnable() interface.

     (4) summary (the original English product will be more flavorful)

      The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. The class must define a method of no arguments called run.
      This interface is designed to provide a common protocol for objects that wish to execute code while they are active. For example, Runnable is implemented by class Thread. Being active simply means that a thread has been started and has not yet been stopped.
       In addition, Runnable provides the means for a class to be active while not subclassing Thread. A class that implements Runnable can run without subclassing Thread by instantiating a Thread instance and passing itself in as the target. In most cases, the Runnable interface should be used if you are only planning to override the run() method and no other Thread methods. This is important because classes should not be subclassed unless the programmer intends on modifying or enhancing the fundamental behavior of the class.

       So far, the implementation interface Runnable of Thead has been understood.


       二、Thread Class(since jdk 1.0)

public class Thread extends Object implements Runnable
       As above, it is the information of the Thread class in the jdk source code, which is explained in detail as follows:

     (1) Nested classes (interfaces)

        1.Thread.State (since jdk 1.5)

        Thread state class, Oracle official explanation: https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.State.html 

        This State class is actually describing the life cycle of a thread, and the transitions between states in the cycle will be explained in subsequent blogs in this series.

         2.Thread.UncaughtExceptionHandler<interface>(since jdk 1.5)

        When a thread is about to terminate due to an uncaught exception, the Java Virtual Machine will query the thread's UncaughtExceptionHandler using Thread.getUncaughtExceptionHandler() and call the handler's uncaughtException method, passing the thread and exception as parameters. If a thread does not explicitly set its UncaughtExceptionHandler, then its ThreadGroup object acts as its UncaughtExceptionHandler. If the ThreadGroup object has no special requirements to handle exceptions, it can forward the call to the default uncaught exception handler.

        

      (2) Field

       MAX_PRIORITY //Maximum thread priority

       MIN_PRIORITY //Minimum thread priority

       NORM _PRIORITY //Default value of thread priority

      

      (3) Constructor

        Combined with Oracle's official documentation and the book "Core Technology of Java Multi-Threading Programming", the constructor of the thread class Thread can be used in 8 ways. The reference is as follows:

Thread()
//Allocates a new Thread object.
Thread(Runnable target)
//Allocates a new Thread object.
Thread(Runnable target, String name)
//Allocates a new Thread object.
Thread(String name)
//Allocates a new Thread object.
Thread(ThreadGroup group, Runnable target)
//Allocates a new Thread object.
Thread(ThreadGroup group, Runnable target, String name)
//Allocates a new Thread object so that it has target as its run object, has the specified name as its name, and belongs to the thread group referred to by group.
Thread(ThreadGroup group, Runnable target, String name, long stackSize)
//Allocates a new Thread object so that it has target as its run object, has the specified name as its name, and belongs to the thread group referred to by group, and has the specified stack size.
Thread(ThreadGroup group, String name)
//Allocates a new Thread object.
        Among them, the Runnable interface, name attribute, ThreadGroup, and stackSize will be selectively matched as its construction parameters. As can be seen in the top mind map, there are generally two ways to create a new thread: 1. Inheriting the Thread class, 2. Implementing the Runnable interface . With the deepening of use and business scenarios, an appropriate Thread construction method can be selected.
      

     (4) Method

       In my opinion, this part is also the most important part of using the Thread class. In the process of learning the basics of Thread, with the evolution of the jdk version, new methods have been added to Thread, and old methods have been replaced. The following will sort out the methods in Thread from the perspective of the evolution of jdk:

       1. Core Method

        In addition to the six categories of methods listed in the above " Mind Map ", several methods that need to be added are as follows:

        1)wait() & notify()

        2)join()

        3)run()

        4) toString() //Returns the string representation of the thread, including the thread's name, priority, and thread group.

        It is very simple, and the specific functions will be introduced in subsequent blogs.


       2. Deprecated (abandoned method)

       1)resum() & suspend

        The reason why the suspend() and resum() methods are abandoned because they will cause thread deadlocks, the official article gives the reasons for considering the abandonment of these two methods:    

         https://docs.oracle.com/javase/7/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html   

       2)countStackFrames()

       This method relies on the suspend() method, so...

       3)stop()

       This method is inherently insecure. Stopping a thread with Thread.stop causes it to unlock all locked monitors (as a natural consequence of the upward propagation of an unchecked ThreadDeath exception). If any objects previously protected by these monitors are in an inconsistent state, the corrupted objects become visible to other threads, potentially leading to arbitrary behavior. Many uses of stop should be replaced by code that simply modifies some variables to indicate that the target thread should stop running. The target thread should check this variable periodically and return in order from its run method if the variable indicates that it will stop running. If the target thread is waiting for a long time (for example, on a condition variable), you should use the interrupt method to interrupt the wait


      3. Methods inherited from class java.lang.Object

equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
      

     (5) Abnormal

       1.IllegalArgumentException

       2.InterruptedException

       3.SecurityException

       4.NullPointerException

       It can be seen that the methods in Thread will cause various exceptions during the calling process, mainly caused by improper handling of method details. By the way, the interrupt() method, together with InterruptException, is a very good way to terminate the thread.


       Finally, a concept is extended: java.util.concurrent concurrent package, which is a package introduced in jdk1.5, and the related interface Callable<V>, which are very important concepts in concurrent programming. Click here, multithreading Subsequent chapters in the series of blogs will explain in detail.


       As mentioned above, through the study of the java.lang.Thread class, you will have a general understanding of the basic concepts and the most commonly used methods of multithreading.





Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325625121&siteId=291194637