Java smallholder cultivation record day 15

Posted by anxiety on Wed, 19 Jan 2022 23:29:29 +0100

day15

Chapter I exceptions

1.1 Java exception handling

Exceptions are some errors in the program, but not all errors are exceptions, and errors can sometimes be avoided.

For example, if your code is missing a semicolon, the result will be an error Java lang.Error; If you use system out. Println (11 / 0), then you will throw Java because you use 0 as the divisor Exception for lang.arithmeticexception.
There are many reasons for exceptions, usually including the following categories:

  • The user entered illegal data.
  • The file to open does not exist.
  • The connection is interrupted during network communication, or the JVM memory overflows.
    Some of these exceptions are caused by user errors, some are caused by program errors, and others are caused by physical errors-
    To understand how Java exception handling works, you need to master the following three types of exceptions:
  • Checking exception: the most representative checking exception is the exception caused by user errors or problems, which cannot be foreseen by programmers. For example, when you want to open a nonexistent file, an exception occurs. These exceptions cannot be simply ignored at compile time.
  • Runtime exceptions: runtime exceptions are exceptions that may be avoided by programmers. In contrast to checking exceptions, runtime exceptions can be ignored at compile time.
  • Error: an error is not an exception, but a problem out of the programmer's control. Errors are usually ignored in code. For example, when the stack overflows, an error occurs, and they cannot be checked during compilation.

1.2 hierarchy of exception class

All exception classes are from Java A subclass inherited by the lang.exception class.
The Exception class is a subclass of the Throwable class. In addition to the Exception class, Throwable also has a subclass Error.
Java programs usually do not catch errors. Errors usually occur in the case of serious failures, which are outside the scope of Java program processing.
Error is used to indicate an error in the runtime environment.
For example, JVM memory overflows. Generally, programs do not recover from errors.
The exception class has two main subclasses: IOException class and RuntimeException class.

1.3 Java built-in exception class

The Java language defines some exception classes in Java Lang standard package.
Subclasses of the standard runtime exception class are the most common exception classes. Because Java Lang package is loaded into all Java programs by default, so most exceptions inherited from runtime exception classes can be used directly.
Java also defines some other exceptions according to each class library. The following table lists Java's non checking exceptions.

abnormaldescribe
ArithmeticExceptionThis exception is thrown when an abnormal operation condition occurs. For example, when an integer is "divided by zero", an instance of this class is thrown.
ArrayIndexOutOfBoundsExceptionAn exception thrown when accessing an array with an illegal index. If the index is negative or greater than or equal to the array size, the index is illegal.
ArrayStoreExceptionAn exception thrown when trying to store an object of the wrong type into an object array.
ClassCastExceptionThis exception is thrown when an attempt is made to cast an object to a subclass that is not an instance.
IllegalArgumentExceptionThe exception thrown indicates that an illegal or incorrect parameter was passed to the method.
IllegalMonitorStateExceptionThe exception thrown indicates that a thread has tried to wait for the monitor of the object, or tried to notify other monitors waiting for the object without specifying the monitor itself.
IllegalStateExceptionA signal generated when a method is called at an illegal or inappropriate time. In other words, the Java environment or Java application is not in the appropriate state required by the requested operation.
IllegalThreadStateExceptionAn exception thrown when a thread is not in the appropriate state required by the requested operation.
IndexOutOfBoundsExceptionIndicates that a sort index (such as sorting an array, string, or vector) is out of range.
NegativeArraySizeExceptionThis exception is thrown if the application attempts to create an array with a negative size.
NullPointerExceptionThis exception is thrown when the application attempts to use null where an object is needed.
NumberFormatExceptionThis exception is thrown when an application attempts to convert a string to a numeric type, but the string cannot be converted to the appropriate format.
SecurityExceptionAn exception thrown by the security manager indicating a security violation.
StringIndexOutOfBoundsExceptionThis exception is thrown by the String method to indicate that the index is either negative or exceeds the size of the String.
UnsupportedOperationExceptionThis exception is thrown when the requested operation is not supported.

The following table lists the Java definitions in Java Lang package.

abnormaldescribe
ClassNotFoundExceptionWhen the application tries to load a class, it cannot find the corresponding class and throws the exception.
CloneNotSupportedExceptionThis exception is thrown when the clone method in the Object class is called to clone an Object, but the Object's class cannot implement the clonable interface.
IllegalAccessExceptionThis exception is thrown when access to a class is denied.
InstantiationExceptionThis exception is thrown when an attempt is made to create an instance of a Class using the newInstance method in the Class class, and the specified Class object cannot be instantiated because it is an interface or an abstract Class.
InterruptedExceptionThis exception is thrown when a thread is interrupted by another thread.
NoSuchFieldExceptionThe requested variable does not exist
NoSuchMethodExceptionThe requested method does not exist

Chapter II exception handling

2.1 throw keyword

/*
throw keyword
 effect:
    You can use the throw keyword to throw the specified exception in the specified method
 Format:
    throw new XXXException("The cause of the abnormality ");
be careful:
    1.throw Keywords must be written inside the method
    2.throw The object behind nev the keyword must be an Exception or a subclass object of Exception
    3.throw Keyword to throw the specified exception object, we must deal with the exception object
        throw After the keyword, RuntimeException or a subclass object of RuntimeException is created. We can not handle it. It is handed over to JWw by default (print exception object and interrupt program)
        throw After the keyword, a compilation exception is created (an error is reported when writing code). We must deal with this exception, either throw or try catch

 */
public class Demo03Throw {
    public static void main(String[] args) {
        int[] arr = new int[3];
        int e = getElement(arr, 3);
        System.out.println(e);
    }
    /*
    Defines a method to get the element at the specified index of the array
    Parameters:
        int[] arr
        int index
    In the future (work), we must first verify the validity of the parameters passed by the method
    If the parameter is illegal, we must use the batch exception method to inform the caller of the method that there is a problem with the passed parameter

     */
    public static int getElement(int[] arr, int index){
        /*
        We can verify the validity of the passed parameter array
        If the value of array arr is nulL
        Then we throw a nuLl pointer exception and tell the caller of the method that "the value of the passed array is nuLl"
         */
        if (arr == null){
            throw new NullPointerException("The value of the array passed is null");
        }
        /*
        We can verify the validity of the passed parameter index
        If the index range is not within the index range of the array
        Then we throw an array index out of bounds exception and tell the caller of the method that "the passed index exceeds the range of use of the array"
         */
        if(index < 0 || index > arr.length - 1){
            throw new ArrayIndexOutOfBoundsException("The index passed is out of range for the array");
        }
        int ele = arr[index];
        return ele;
    }
}

Objects non null judgment
Remember when we learned about an object class? It was mentioned that it consists of some static practical methods. These methods are null save (null pointer safe) or null tolerance (null pointer tolerant). In its source code, it throws an exception to the null value of the object.

  • Public static < T > t requirenonnull (t obj): check that the specified reference object is not null.
    Looking at the source code, we found that an exception was thrown for null:
public static <T> T requireNonNull(T obj) {
	if (obj -= null)
		throw new NullPointerException( ) ;
	return obj;
}
import java.util.Objects;

/*
    Objects Static methods in class:
    public static <T> T requireNonNull(T obj):View that the specified reference object is not null.
    Looking at the source code, we found that an exception was thrown for null:

    public static <T> T requireNonNull(T obj) {
        if (obj -= null)
            throw new NullPointerException( ) ;
        return obj;
    }
 */
public class Demo04Objects {
    public static void main(String[] args) {
        method(null);
    }

    public static void method(Object obj){
        //Make legal judgment on the passed parameters to judge whether they are null
        /*if(obj == null){
            throw new NullPointerException("The object value passed is null ');
        }*/
        //Objects.requireNonNull(obj);
        Objects.requireNonNull(obj, "Null pointer exception");
    }
}

2.2 declare exception throws

Declare exception: identify the problem and report it to the caller. If a compile time exception is thrown through throw in the method without capture and processing (this method will be explained later), it must be declared through throws for the caller to handle.
The keyword throws is used on the method declaration to indicate that the current method does not handle exceptions, but reminds the caller of the method to handle exceptions (throw exceptions)
Declaration exception format:

Modifier return value type method name(parameter) throws Exception class name 1,Exception class name 2...{}
import java.io.FileNotFoundException;
import java.io.IOException;

/*
    throws Keyword: the first method of exception handling, which is handed over to others for handling
    effect:
        When an exception object is thrown inside a method, we must deal with the exception object
        You can use the throws keyword to handle the exception object. The exception object declaration will be thrown to the caller of the method for processing (you will not handle it yourself, but others), and finally handed over to JW for processing -- > interrupt processing
    Use format: used in method declaration
        Modifier return value type method name (parameter list) throws AAAException,BBBException {
            throw new AAAException("Cause ");
            throw new 8BBException( "Cause ");
        }
    be careful:
        1.throws Keywords must be written at the method declaration
        2.throws The Exception declared after the keyword must be an Exception or a subclass of Exception
        3.If multiple exception objects are thrown inside the method, multiple exceptions must also be declared after throws
        If multiple exception objects thrown have a child parent relationship, you can declare the parent exception directly
        4.If we call a method that declares to throw an exception, we must handle the declared exception
        Or continue to use the throws declaration to throw it, give it to the caller of the method for processing, and finally give it to the JVM
        Or try Catch handles exceptions by itself

 */
public class Demo05Throws {
    /*
    FileNotFoundException extends IOException
    If multiple exceptions thrown have a child parent relationship, you can declare the parent exception directly
     */
    public static void main(String[] args) throws FileNotFoundException, IOException {
        readFile("c:\\a.xt");
    }
    /*
        Define a method to judge the legitimacy of the transmitted file path
        If the path is not "c:\a.txt", we will throw the file and tell the caller of the method that the exception object cannot be found
        be careful:
            FileNotFoundException It is a compilation exception. If a compilation exception is thrown, it must be handled
            You can use the throws declaration to throw FileNotFoundException, an exception object, for the caller of the method to handle
     */
    public static void readFile(String fileName) throws FileNotFoundException, IOException {
        if (!fileName.equals("c:\\a.txt")){
            throw new FileNotFoundException("The file path passed is not c:\\a.txt");
        }
        /*
            If the path passed is not txt end
            Then we throw an Io exception object to tell the caller of the method that the file suffix is wrong
         */
        if (!fileName.endsWith(".txt")){
            throw new IOException("The suffix of the file is incorrect");
        }
        System.out.println("There is no problem with the path. Read the file");

    }
}

2.3 catch exception try...... catch

If an exception occurs, the program will be terminated immediately, so we have to deal with the exception:

  1. The method does not handle, but declares throws, which are handled by the caller of the method.
  2. Use the try catch statement block in the method to handle exceptions.
    The way to try catch is to catch exceptions.
  • Catch exception: in Java, the exception specific statements are caught, and the exceptions can be handled in a specified way. The syntax for catching exceptions is as follows:
try{
	Write code that may cause exceptions
}catch(Exception type e){
	Code to handle exceptions
	//Log / print exception information / continue to throw exception
}

Three exception handling methods are defined in the Throwable class
String getMessage() returns a short description of this throwable.
String toString() returns the detailed message string of this throwable.
void printStackTrace() JVM prints exception objects. This method is used by default. The printed exception information is the most comprehensive

import java.io.FileNotFoundException;
import java.io.IOException;

/*
    try......catch:The second way of exception handling is to handle exceptions by yourself
        Format;

            try{
                Code that may cause exceptions
            }catch(Define an exception variable to receive the exception object thrown in the try){
                Exception handling logic, how to handle the exception object after the exception object
                In general, abnormal information will be recorded in a log during work
            }
            ...
            catch (Exception class name (variable name){
            }
        be careful:
            1.try Multiple exception objects may be thrown in, so you can use multiple catch es to handle these exception objects
            2.If an exception occurs in try, the exception handling logic in catch will be executed. After executing the handling logic in catch, continue to execute try Code after catch
            If there is no exception in the try, the exception handling logic in catch will not be executed, and the code in the try will be executed. Continue! Continue to try Code after catch

 */
public class Demo01TryCatch {
    public static void main(String[] args) {
        try{
            //Code that may cause exceptions
            readFile("d:\\a.tx");
        }catch (IOException e){//catch defines exception variables to receive exception objects thrown in try
            //Exception handling logic, how to handle the exception object after the exception object

            //System.out.println("catch - the file suffix passed is not. txt");

            /*
                Throwable Class defines three exception handling methods
                String getMessage() Returns a short description of this throwable.
                String toString() Returns the detailed message string for this throwable.
                void printStackTrace() JVM This method is used by default to print exception objects. The printed exception information is the most comprehensive
             */

            System.out.println(e.getMessage());//The suffix of the file is incorrect
            System.out.println(e.toString());//Rewrite toString of Object class, Java io. IOException: the suffix of the file is incorrect
            System.out.println(e);//java.io.IOException: the suffix of the file is incorrect

            /*
                java.io.IOException: The suffix of the file is incorrect
                at demo02.Exception.Demo01TryCatch.readFile(Demo01TryCatch.java:61)
                at demo02.Exception.Demo01TryCatch.main(Demo01TryCatch.java:29)

             */
            e.printStackTrace();
        }
        System.out.println("Subsequent code");
    }

         /*
            If the path passed is not txt end
            Then we throw an Io exception object to tell the caller of the method that the file suffix is wrong
         */
    public static void readFile(String fileName) throws FileNotFoundException, IOException {
        /*if (!fileName.equals("c:\\a.txt")){
            throw new FileNotFoundException("The file path passed is not c:\a.txt ");
        }*/

        if (!fileName.endsWith(".txt")){
            throw new IOException("The suffix of the file is incorrect");
        }
        System.out.println("There is no problem with the path. Read the file");

    }
}

2.4 multiple capture blocks

The case where a try code block is followed by multiple catch code blocks is called multiple capture.
The syntax of multiple capture blocks is as follows:

try{
   // Program code
}catch(Variable name of exception type 1){
  // Program code
}catch(Variable name of exception type 2){
  // Program code
}catch(Variable name of exception type 3){
  // Program code
}

The above code snippet contains three catch blocks.
You can add any number of catch blocks after a try statement.
If an exception occurs in the protection code, the exception is thrown to the first catch block.
If the data type of the exception thrown matches ExceptionType1, it will be caught here.
If it does not match, it is passed to the second catch block.
This is done until the exception is caught or passed through all catch blocks.
example
This example shows how to use multiple try/catch.

try {
    file = new FileInputStream(fileName);
    x = (byte) file.read();
} catch(FileNotFoundException f) { // Not valid!
    f.printStackTrace();
    return -1;
} catch(IOException i) {
    i.printStackTrace();
    return -1;
}

be careful:
If the exception variable defined in catch has a child parent relationship, the exception variable of the child class must be written above, otherwise an error will be reported

2.5 finally keyword

finally keyword is used to create a code block that executes after a try code block.
Whether or not an exception occurs, the code in the finally code block will always be executed.
In the finally code block, you can run closing statements such as cleanup types.

import java.io.FileNotFoundException;
import java.io.IOException;

/*
    finaLLy Code block format:
    try{
        Code that may cause exceptions
    }catch(Define an exception variable to receive the exception object thrown in the try){
        Exception handling logic, how to handle the exception object after the exception object
        In general, abnormal information will be recorded in a log during work
    }
    catch(Exception class name (variable name){

    }finally{
        It is executed regardless of whether an exception occurs
        }
    be careful:
        1.finalLy It cannot be used alone. It must be used with try
        2.finally It is generally used for resource release (resource recovery). No matter whether the program is abnormal or not, the resource should be released (IO) at last
 */
public class Demo02TryCatchFinally {
    public static void main(String[] args){
        try {
            //Code that may generate exceptions
            readFile("c:\\a.xt");
        } catch (IOException e) {
            //Exception handling logic
            e.printStackTrace();
        }finally {
            //Whether an exception occurs or not, it is executed
            System.out.println("Resource release");
        }
    }

    public static void readFile(String fileName) throws FileNotFoundException, IOException {
        if (!fileName.equals("c:\\a.txt")){
            throw new FileNotFoundException("The file path passed is not c:\\a.txt");
        }
        /*
            If the path passed is not txt end
            Then we throw an Io exception object to tell the caller of the method that the file suffix is wrong
         */
        if (!fileName.endsWith(".txt")){
            throw new IOException("The suffix of the file is incorrect");
        }
        System.out.println("There is no problem with the path. Read the file");

    }
}

Note the following:

  • catch cannot exist independently of try.
  • It is not mandatory to add a finally block after try/catch.
  • try code cannot be followed by neither catch nor finally blocks.
  • No code can be added between try, catch and finally blocks.
  • If finally has a return statement, always return the result in finally to avoid this situation
/*
If finally has a return statement, always return the result in finally to avoid this situation
 */
public class Demo02Exception {
    public static void main(String[] args) {
        System.out.println(getA());//100
    }
    public static int getA(){
        int a = 10;
        try{
            return a;
        }catch (Exception e){
            System.out.println(e);
        }finally {
            a = 100;
            return a;
        }
    }
}
/*
    Exception of child parent class:
        -If the parent class throws multiple exceptions, when overriding the parent class method, the child class throws the same exception as the parent class, or the child of the parent class exception, or does not throw an exception.
        -The parent class method does not throw an exception, and the child class cannot throw an exception when overriding the parent class method. At this time, the subclass generates the exception, which can only be caught and processed, and cannot be declared and thrown
    be careful:
        When the parent class is abnormal, the child class is abnormal
 */
public class Fu {
    public void show01() throws NullPointerException, ClassCastException{}
    public void show02() throws IndexOutOfBoundsException{}
    public void show03() throws IndexOutOfBoundsException{}
    public void show04() {}
}
class Zi extends Fu{
    //When a subclass overrides a parent class method, it throws the same exception as the parent class
    public void show01() throws NullPointerException, ClassCastException{}
    //A subclass that throws a superclass exception when overriding a superclass method
    public void show02() throws ArrayIndexOutOfBoundsException{}
    //Subclasses do not throw exceptions when overriding parent methods
    public void show03() {}
    /*
        The parent class method does not throw an exception, and the child class cannot throw an exception when overriding the parent class method
        At this time, the subclass generates the exception, which can only be caught and processed, and cannot be declared and thrown
     */
    public void show04() {
        try{
            throw new Exception ("Compiler exception");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2.6 custom exception

In Java, you can customize exceptions. When writing your own exception class, you need to keep the following points in mind.

  • All exceptions must be subclasses of Throwable.
  • If you want to write a checking Exception class, you need to inherit the Exception class.
  • If you want to write a runtime exception class, you need to inherit the RuntimeException class.
/*
    Custom exception class:
        java The provided exception classes are not enough for us to use. We need to define some exception classes ourselves
    Format:
        public class XXXException extends Exception / RuntimeException{
            Construction method of adding an empty parameter
            Add a construction method with exception information

        }
    be careful:
        1.Custom Exception classes generally end with Exception, indicating that this class is an Exception class
        2.Custom Exception class, must inherit Exception or RuntimeException
            Inherit Exception: then the custom Exception class is a compile time Exception. If a compile time Exception is thrown inside the method, you must handle the Exception, either throw or try catch
            Inherit RuntimeException: then the custom exception class is a runtime exception, which needs no processing and is handed over to the virtual machine for processing (interrupt processing)

 */
public class RegisterException extends Exception{
    //Construction method of adding an empty parameter

    public RegisterException() {
    }
    //Add a constructor with exception information
    //Looking at the source code, it is found that all exception classes will have a constructor with exception information. The constructor with exception information of the parent class will be called inside the method to let the parent class handle the exception information
    public RegisterException(String message) {
        super(message);
    }
}

2.7 custom exception class exercise

import java.util.Scanner;

/*
    Requirements: we simulate the registration operation. If the user name already exists, we throw an exception and prompt: pro, the user name has been registered.
    analysis:
        1.Use the array to save the registered user name (database)
        2.Use Scanner to obtain the registered user name entered by the user (front end, page)
        3.Define a method to judge the user name registered in the user input
            Traverse the array storing registered user names to obtain each user name
            Compare the obtained user name with the user name entered by the user
            true:
                If the user name already exists, a RegisterException exception will be thrown to tell the user "pro, the user name has been registered";
            false:
                Continue to traverse the comparison
                If the cycle ends and no duplicate user name is found, the user will be prompted "Congratulations, registration is successful;
 */
public class Demo01RegisterException {
    //1. Use the array to save the registered user name (database)
    static String[] userNames = {"Zhang San","Li Si","Wang Wu"};
    //2. Use Scanner to obtain the registered user name entered by the user (front end, page)
    public static void main(String[] args) /*throws RegisterException*/ {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter the user name you want to register:");
        String username = sc.next();
        checkUserName(username);
    }

    //3. Define a method to judge the user name registered in the user input
    public static void checkUserName(String username) /*throws RegisterException*/ {
        //Traverse the array storing registered user names to obtain each user name
        for (String name : userNames){
            if (name.equals(username)){
                //true: the user name already exists, throw a RegisterException exception, and tell the user "pro, the user name has been registered";
                try {
                    throw new RegisterException("Pro, the user has been registered");
                } catch (RegisterException e) {
                    e.printStackTrace();
                    return;
                }
            }
        }
        //If the cycle ends and no duplicate user name is found, the user will be prompted "Congratulations, registration is successful;
        System.out.println("Congratulations on your successful registration");
    }
}

2.8 general exceptions

Two types of exceptions and errors are defined in Java.

  • JVM(
  • Java (virtual machine) exception: an exception or error thrown by the JVM. For example: NullPointerException class, ArrayIndexOutOfBoundsException class, ClassCastException class.
  • Program level exception: an exception thrown by a program or API program. For example, the IllegalArgumentException class and the IllegalStateException class.

Chapter 3 multithreading

3.1 concurrency and parallelism

**Concurrency: * * refers to two or more events occurring in the same time period.
**Parallel: * * means that two or more events occur at the same time (at the same time)

3.2 threads and processes

**Process: * * refers to an application running in memory. Each process has an independent memory space. An application can run multiple processes at the same time; Process is also an execution process of the program and the basic unit for the system to run the program; the system running a program is the process of a process from creation, running to extinction.
**Thread: * * thread is an execution unit in a process, which is responsible for the execution of programs in the current process. There is at least one thread in a process. There can be multiple threads in a process, and this application can also be called a multithreaded program.
In short: after a program runs, there is at least one process, and a process can contain multiple threads
Thread scheduling:

  • Time sharing dispatcher
    All threads use the right to use the CPU in turn, and allocate the CPU time of each thread equally.
  • preemptive scheduling
    Give priority to the threads with high priority to use CPU. If the threads have the same priority, one will be selected randomly (thread randomness). Java uses preemptive scheduling.

3.3 Java multithreaded programming

Java provides built-in support for multithreaded programming. A thread refers to a single sequential control flow in a process. Multiple threads can be concurrent in a process, and each thread executes different tasks in parallel.
Multithreading is a special form of multitasking, but multithreading uses less resource overhead.
Another term related to threads is defined here - process: a process includes memory space allocated by the operating system and contains one or more threads. A thread cannot exist independently. It must be part of a process. A process runs until all non daemon threads have finished running.
Multithreading can satisfy programmers to write efficient programs to make full use of CPU.

3.4 create thread class

Main thread: the thread that executes the main method
Single threaded program: there is only one thread in the java program. The execution starts from the main method and runs from top to bottom. The JVM executes the main method. The main method will enter the stack memory. The JVM will find the operating system to open up an execution path from the main method to the cpu. The cpu can execute the main method through this path, and this path has a name, which is called the main thread.

Create a thread
Java provides three ways to create threads:

  • By inheriting the Thread class itself;
  • Through the implementation of Runnable interface;
  • Create threads through Callable and Future.

Method 1: inherit the Thread class itself

Java uses Java Lang. Thread class represents threads. All Thread objects must be instances of Thread class or its subclasses. The role of each Thread is to complete a certain task. In fact, it is to execute a program flow, that is, a piece of code executed in sequence. Java uses Thread executors to represent this program flow. The steps to create and start a multithread by inheriting the Thread class in Java are as follows:

  1. Define the subclass of Thread class and rewrite the run() method of this class. The method body of the run() method represents the task that the Thread needs to complete. Therefore, the run() method is called the Thread execution body.
  2. Create an instance of Thread subclass, that is, create a Thread object
  3. Call the start() method of the thread object to start the thread
/*
    The first way to create a multithreaded program: create a subclass of the Thread class
    java.lang.Thread Class: a class that describes threads. If we want to implement multithreaded programs, we must inherit the Thread class

    Implementation steps:
        1.Create a subclass of the Thread class
        2.Override the run method in the Thread class in the subclass of the Thread class and set the Thread task (what do you want to do to start the Thread?)
        3.Create a subclass object of the Thread class
        4.Call the start method in the Thread class to start a new Thread and execute the run method
            void start()Start the thread to execute; The Java virtual machine calls the run method of the thread.
            The result is that two threads run concurrently; The current thread (main thread) and another thread (the new thread created executes its run method)
            It is illegal to start a thread multiple times. Especially when the thread has finished execution, it cannot be restarted.
        java The program belongs to preemptive scheduling. The thread has high priority and the thread has priority to execute; At the same priority, select one execution at random

 */
 
 //1. Create a subclass of Thread class
public class MyThread extends Thread {
    //2. Override the run method in the Thread class in the subclass of the Thread class and set the Thread task (what do you want to do to start the Thread?)

    @Override
    public void run() {
        for (int i = 0; i < 20; i++){
            System.out.println("run" + i);
        }
    }
}
public class Demo01Thread {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();
        for (int i = 0; i < 20; i++) {
            System.out.println("main" + i);
        }
    }
}

Multithreading principle_ Random printing

Multithreading principle_ Multithreaded memory diagram

In the process of completing the operation, we used java Lang. thread class, API. This class defines some methods related to threads, as follows:
Construction method:

  • public Thread(): allocate a new thread object.
  • public Thread(String name): assign a new thread object with a specified name.
  • public Thread(Runnable target): allocate a new thread object with the specified target.
  • public Thread(Runnable target,String name): allocate a new thread object with the specified target and specify the name.
    Common methods:
  • public string getName(): get the name of the current thread.
  • public void start(): causes this thread to start executing; The Java virtual machine calls the run method of this thread.
  • public void run(): the task to be executed by this thread defines the code here.
  • Public static void sleep (long miles): pauses (temporarily stops) the currently executing thread for a specified number of milliseconds.
  • public static Thread currentThread(): returns a reference to the currently executing thread object.
/*
    Get the name of the thread:
        1.Use the method getName() in the Thread class
            String getName() Returns the name of the thread.
        2.You can first get the thread currently executing, and use the method getName() in the thread to get the name of the thread
            static Thread currentThread()Returns a reference to the thread object currently executing.
 */
public class MyThread extends Thread{
    @Override
    public void run() {
//        String name = getName();
//        System.out.println(name);
        Thread t = currentThre();
        System.out.println(t);
        String name = t.getName();
        System.out.println(name);
    }
}
/*
    Name of thread:
        main thread: main
        New thread: thread-0, thread-1, thread-2

 */
public class Demo01GetThreadName {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();
        //Gets the main of the main thread
        System.out.println(Thread.currentThread().getName());
    }
}
/*
    Set the name of the thread: (learn)
    1.Use the method setname (name) in the Thread class
        void setName (String name)Change the thread name to be the same as the parameter name.
    ⒉.Create a construction method with parameters, and pass the name of the thread with parameters; Call the parameterized construction method of the parent class, pass the thread name to the parent class, and let the parent class (Thread) give a name to the child thread
        Thread (String name)Assign a new Thread object.

 */
public class MyThread extends Thread{
    public MyThread(){}
    public MyThread(String name){
        super(name);
    }
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}
public class Demo01SetThreadName {
    public static void main(String[] args) {
        MyThread mt = new MyThread();
        mt.setName("cockroach");
        mt.start();

        //Turn on Multithreading
        new MyThread("Wangcai").start();
    }
}
/*
    public static void sleep(Long millis):Causes the thread currently executing to pause (temporarily stop execution) for the specified number of milliseconds.
    After the end of milliseconds, the thread continues to execute
 */
public class Demoi01Sleep {
    public static void main(String[] args) {
        for (int i = 0; i < 60; i++) {
            System.out.println(i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

Method 2: implement Runnable interface

/*
    The second way to create a multithreaded program is to implement the Runnable interface
    java.Lang. Runnable
        Runnable Interfaces should be implemented by classes that intend to execute their instances through a thread. Class must define a parameterless method called run.
    java.Lang. Thread Class construction method
        Thread(Runnable target)Assign a new Thread object.
        Thread ( Runnable target,string name)Assign a new Thread object.
    Implementation steps:
        1.Create an implementation class of Runnable interface
        2.Override the run method of the Runnable interface in the implementation class to set the thread task
        3.Create an implementation class object of Runnable interface
        4.Create a Thread class object and construct the implementation class object passing the Runnable interface in the method
        5.Call the start method in the Thread class to start a new Thread to execute the run method
	Benefits of implementing Runnable interface to create multithreaded programs:
		1.The limitation of single inheritance is avoided
			A class can only inherit one class (a person can only have one parent). If a class inherits Thread class, it cannot inherit other classes
			The Runnable interface is implemented. You can also inherit other classes and implement other interfaces
		2.It enhances the expansibility of the program and reduces the coupling (decoupling) of the program
			The way to implement the Runnable interface separates (decouples) setting the thread task from starting a new thread
			In the implementation class, the run method is overridden: it is used to set the thread task
			Create a Thread class object and call the start method: used to start a new Thread
 */
 
 //1. Create an implementation class of Runnable interface
public class RunnableImpl implements Runnable {
    //2. Rewrite the run method of the Runnable interface in the implementation class to set the thread task
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            System.out.println(Thread.currentThread().getName() + "-->" + i);
        }
    }
}
public class Demo01Runnable {
    public static void main(String[] args) {
        //3. Create an implementation class object of Runnable interface
        RunnableImpl run = new RunnableImpl();
        //4. Create a Thread class object and construct the implementation class object passing the Runnable interface in the method
        Thread t = new Thread(run);
        //5. Call the start method in the Thread class to start a new Thread to execute the run method
        t.start();
        for (int i = 0; i < 20; i++) {
            System.out.println(Thread.currentThread().getName() + "-->" + i);
        }
    }
}

Method 3: create threads through Callable and Future

  1. Create the implementation class of the Callable interface and implement the call() method, which will be used as the thread executor and have a return value.
  2. Create an instance of the Callable implementation class, and use the FutureTask class to wrap the Callable object, which encapsulates the return value of the call() method of the Callable object.
  3. Create and start a new Thread using the FutureTask object as the target of the Thread object.
  4. Call the get() method of the FutureTask object to get the return value after the execution of the child thread.
public class CallableThreadTest implements Callable<Integer> {
    public static void main(String[] args)  
    {  
        CallableThreadTest ctt = new CallableThreadTest();  
        FutureTask<Integer> ft = new FutureTask<>(ctt);  
        for(int i = 0;i < 100;i++)  
        {  
            System.out.println(Thread.currentThread().getName()+" Cyclic variable of i Value of"+i);  
            if(i==20)  
            {  
                new Thread(ft,"Thread with return value").start();  
            }  
        }  
        try  
        {  
            System.out.println("Return value of child thread:"+ft.get());  
        } catch (InterruptedException e)  
        {  
            e.printStackTrace();  
        } catch (ExecutionException e)  
        {  
            e.printStackTrace();  
        }  
  
    }
    @Override  
    public Integer call() throws Exception  
    {  
        int i = 0;  
        for(;i<100;i++)  
        {  
            System.out.println(Thread.currentThread().getName()+" "+i);  
        }  
        return i;  
    }  
}

Comparison of three ways to create threads

  1. When multithreading is created by implementing Runnable and Callable interfaces, the thread class only implements the Runnable interface or Callable interface, and can also inherit other classes.
  2. When creating a multithread by inheriting the Thread class, it is easy to write. If you need to access the current Thread, you do not need to use Thread The currentthread() method can directly use this to obtain the current Thread.

Topics: Java Back-end