Java language foundation Day21 (exception, exception handling, exception precautions, custom exception class, multithreading)

Posted by dansk on Thu, 06 Jan 2022 00:43:11 +0100

1, Abnormal

1. Anomaly concept & anomaly system

Anomaly concept

Abnormal means abnormal. In life: the doctor said that there is an abnormality in a part of your body, which is a little different from normal, and the function of this part will be affected In the program, it means:

  • Exception: refers to an abnormal situation during the execution of the program, which will eventually lead to the abnormal stop of the JVM.

In object-oriented programming languages such as Java, the exception itself is a class. Generating an exception is to create an exception object and throw an exception object. The way Java handles exceptions is interrupt handling.

An exception does not refer to a syntax error. If the syntax is wrong and the compilation fails, a bytecode file will not be generated and cannot run at all.

Abnormal system

The exception mechanism actually helps us find problems in the program.

The root class of the exception is Java lang.Throwable
There are two subclasses under it: Java Lang. error and Java lang.Exception ,
The usual exception refers to Java lang.Exception

Throwable system:
Error: a serious error. An error that cannot be handled can only be avoided in advance, like a terminal disease.
Exception: indicates an exception. After an exception is generated, the programmer can correct it through code to make the program continue to run. It must be handled. Like cold, appendicitis.

2. Anomaly classification

package com.itheima.demo01.Exception;

/*
    java.lang.Throwable:Class is a superclass for all errors or exceptions in the Java language.
        Exception:Compile time exceptions, problems in compiling (writing code) java programs
            RuntimeException:Run time exceptions, problems in the running process of java programs
            The exception is equivalent to a small problem (cold, fever) in the program. Deal with the exception and the program can continue to execute (take some medicine and continue the revolutionary work)
        Error:error
            A mistake is equivalent to an incurable disease in the program (SARS, AIDS) The source code must be modified before the program can continue
 */
public class Demo01Exception {
    public static void main(String[] args) /*throws ParseException*/ {
        //Exception: compile time exception, which is a problem in compiling (writing code) java programs
        /*SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//Used to format the date
        Date date = null;
        try {
            date = sdf.parse("1999-0909");//Parse the Date in string format into Date format
        } catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.println(date);*/

        //RuntimeException: run-time exception, a problem that occurs during the running of a java program
        /*int[] arr = {1,2,3};
        //System.out.println(arr[0]);
        try {
            //Code with possible exceptions
            System.out.println(arr[3]);
        }catch(Exception e){
            //Exception handling logic
            System.out.println(e);
        }*/

        /*
            Error:error
            OutOfMemoryError: Java heap space
            Memory overflow error. The array created is too large and exceeds the memory allocated to the JVM
         */
        //int[] arr = new int[1024*1024*1024];
        //The code must be modified to create a smaller array
        int[] arr = new int[1024*1024];
        System.out.println("Subsequent code");
    }
}

3. Analysis of abnormal generation process

2, Exception handling

1.throw keyword

package com.itheima.demo01.Exception;
/*
    throw keyword
    effect:
        You can use the throw keyword to throw the specified exception in the specified method
    Use format:
        throw new xxxException("Cause of abnormality ");
    be careful:
        1.throw Keywords must be written inside the method
        2.throw The object of new after 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 the JVM for processing 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 = null;
        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 throw an exception to inform the caller of the method that there is a problem with the passed parameter
        be careful:
            NullPointerException It is a runtime exception. We don't need to handle it. It is handed over to the JVM by default
            ArrayIndexOutOfBoundsException It is a runtime exception. We don't need to handle it. It is handed over to the JVM by default
     */
    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;
    }
}

2.Objects non null judgment requireNonNull method

package com.itheima.demo01.Exception;

import java.util.Objects;

/*
    Obects Static methods in classes
    public static <T> T requireNonNull(T obj):View that the specified reference object is not null.
    Source code:
        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){
        //Judge the validity of the passed parameters to determine whether they are null
        /*if(obj == null){
            throw new NullPointerException("The value of the object passed is null ');
        }*/

        //Objects.requireNonNull(obj);
        Objects.requireNonNull(obj,"The value of the object passed is null");
    }
}

3. Declare exception throws

throws keyword the first way to handle exceptions: leave it to others

package com.itheima.demo01.Exception;

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 the JVM for processing -- > interrupt processing
    Use format: used in method declaration
        Modifier return value type method name (parameter list) throws aaaexcepton, bbbexcepton {
            throw new AAAExcepiton("Cause ");
            throw new BBBExcepiton("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 directly declare the parent exception
        4.If we call a method that declares that an exception is thrown, 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 extends Excepiton
        If multiple exception objects thrown have a child parent relationship, you can directly declare the parent exception
     */
    //public static void main(String[] args) throws FileNotFoundException,IOException {
    //public static void main(String[] args) throws IOException {
    public static void main(String[] args) throws Exception {
        readFile("c:\\a.tx");
    }

    /*
        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 file");
    }
}

The second method of trycatch exception handling: handle exceptions yourself

package com.itheima.demo02.Exception;

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. After executing the code in the try, continue to execute the 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");
        }
        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 IOException {

        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 file");
    }
}

The second method of trycatch exception handling: three exception handling methods in the Throwable class

package com.itheima.demo02.Exception;

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. After executing the code in the try, continue to execute the 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());// Override toString Java. Java of Object class 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 com.itheima.demo02.Exception.Demo01TryCatch.readFile(Demo01TryCatch.java:55)
                    at com.itheima.demo02.Exception.Demo01TryCatch.main(Demo01TryCatch.java:27)
             */
            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 IOException {

        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 file");
    }
}

The second method of trycatch exception handling: finally code block

package com.itheima.demo02.Exception;

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.tx");
        } catch (IOException e) {
            //Exception handling logic
            e.printStackTrace();
        } finally {
            //Whether an exception occurs or not, it is executed
            System.out.println("Resource release");
        }
    }

    /*
       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 IOException {

        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 file");
    }
}

3, Abnormal precautions

1. Exception precautions: capture and handling of multiple exceptions

package com.itheima.demo03.Exception;

import java.util.List;

/*
    Abnormal precautions
 */
public class Demo01Exception {
    public static void main(String[] args) {
        /*
            How to deal with multiple exceptions using capture?
            1. Multiple exceptions are handled separately.
            2. Multiple exceptions are captured once and processed multiple times.
            3. Multiple exceptions are captured and processed at a time.
         */

        //1. Handle multiple exceptions separately.
       /* try {
            int[] arr = {1,2,3};
            System.out.println(arr[3]);//ArrayIndexOutOfBoundsException: 3
        }catch (ArrayIndexOutOfBoundsException e){
            System.out.println(e);
        }

        try{
            List<Integer> list = List.of(1, 2, 3);
            System.out.println(list.get(3));//IndexOutOfBoundsException: Index 3 out-of-bounds for length 3
        }catch (IndexOutOfBoundsException e){
            System.out.println(e);
        }*/

        //2. Multiple exceptions are captured at one time and processed multiple times.
        /*try {
            int[] arr = {1,2,3};
            //System.out.println(arr[3]);//ArrayIndexOutOfBoundsException: 3
            List<Integer> list = List.of(1, 2, 3);
            System.out.println(list.get(3));//IndexOutOfBoundsException: Index 3 out-of-bounds for length 3
        }catch (ArrayIndexOutOfBoundsException e){
            System.out.println(e);
        }catch (IndexOutOfBoundsException e){
            System.out.println(e);
        }*/

        /*
            Precautions for one try multiple catch es:
                catch For the exception variable defined inside, if there is a child parent relationship, the exception variable of the child class must be written above, otherwise an error will be reported
                ArrayIndexOutOfBoundsException extends IndexOutOfBoundsException
         */
        /*try {
            int[] arr = {1,2,3};
            //System.out.println(arr[3]);//ArrayIndexOutOfBoundsException: 3
            List<Integer> list = List.of(1, 2, 3);
            System.out.println(list.get(3));//IndexOutOfBoundsException: Index 3 out-of-bounds for length 3
        }catch (IndexOutOfBoundsException e){
            System.out.println(e);
        }catch (ArrayIndexOutOfBoundsException e){
            System.out.println(e);
        }*/

        //3. Multiple exceptions are captured and processed at one time.
        /*try {
            int[] arr = {1,2,3};
            //System.out.println(arr[3]);//ArrayIndexOutOfBoundsException: 3
            List<Integer> list = List.of(1, 2, 3);
            System.out.println(list.get(3));//IndexOutOfBoundsException: Index 3 out-of-bounds for length 3
        }catch (Exception e){
            System.out.println(e);
        }*/

        //The runtime exception is thrown and can not be handled. Neither capture nor declare throw.
        //The default is for the virtual machine to process and terminate the program. When will the runtime exception not be thrown and continue to execute the program
        int[] arr = {1,2,3};
        System.out.println(arr[3]);//ArrayIndexOutOfBoundsException: 3
        List<Integer> list = List.of(1, 2, 3);
        System.out.println(list.get(3));//IndexOutOfBoundsException: Index 3 out-of-bounds for length 3

        System.out.println("Subsequent code!");
    }
}

2. Exception precautions finally has a return statement

package com.itheima.demo03.Exception;
/*
    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) {
        int a = getA();
        System.out.println(a);
    }

    //Define a method that returns the value of variable a
    public static int getA(){
        int a = 10;
        try{
            return a;
        }catch (Exception e){
            System.out.println(e);
        }finally {
            //Code that must execute
            a = 100;
            return a;
        }

    }
}

3. Exception precautions: child and parent class exceptions

package com.itheima.demo03.Exception;
/*
    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() throws Exception {}
}

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 parent exception when overriding a parent 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.

     */
    //public void show04() throws Exception{}

    //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("Compile time exception");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

4, Custom exception class

1. General

package com.itheima.demo04.MyException;
/*
    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 XXXExcepiton extends Exception | RuntimeException{
            Construction method of adding an empty parameter
            Add a constructor 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
            Inheriting RuntimeException: the custom exception class is a runtime exception that 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(){
        super();
    }

    /*
        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. Practice of customizing exception classes

package com.itheima.demo04.MyException;
/*
    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 XXXExcepiton extends Exception | RuntimeException{
            Construction method of adding an empty parameter
            Add a constructor 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
            Inheriting RuntimeException: the custom exception class is a runtime exception that 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(){
        super();
    }

    /*
        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);
    }
}

package com.itheima.demo04.MyException;

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, throw a RegisterException exception 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 with "Congratulations, successful registration!";
 */
public class Demo01RegisterException {
    // 1. Use the array to save the registered user name (database)
    static String[] usernames = {"Zhang San","Li Si","Wang Wu"};

    public static void main(String[] args) /*throws RegisterException*/ {
        //2. Use Scanner to obtain the registered user name entered by the user (front end, page)
        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) {
            //Compare the obtained user name with the user name entered by the user
            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 name has been registered");
                } catch (RegisterException e) {
                    e.printStackTrace();
                    return; //End method
                }
            }
        }

        //If the cycle ends and no duplicate user name is found, the user will be prompted with "Congratulations, successful registration!";
        System.out.println("Congratulations,login was successful!");
    }
}

package com.itheima.demo04.MyException;
/*
    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 XXXExcepiton extends Exception | RuntimeException{
            Construction method of adding an empty parameter
            Add a constructor 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
            Inheriting RuntimeException: the custom exception class is a runtime exception that needs no processing and is handed over to the virtual machine for processing (interrupt processing)
 */
public class RegisterException extends /*Exception*/ RuntimeException{
    //Construction method of adding an empty parameter
    public RegisterException(){
        super();
    }

    /*
        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);
    }
}

package com.itheima.demo04.MyException;

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, throw a RegisterException exception 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 with "Congratulations, successful registration!";
 */
public class Demo02RegisterException {
    // 1. Use the array to save the registered user name (database)
    static String[] usernames = {"Zhang San","Li Si","Wang Wu"};

    public static void main(String[] args) {
        //2. Use Scanner to obtain the registered user name entered by the user (front end, page)
        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)  {
        //Traverse the array storing registered user names to obtain each user name
        for (String name : usernames) {
            //Compare the obtained user name with the user name entered by the user
            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";
                throw new RegisterException("Pro, the user name has been registered");//Throw run-time exceptions without processing, and hand them over to the JVM for processing and interrupt processing
            }
        }

        //If the cycle ends and no duplicate user name is found, the user will be prompted with "Congratulations, successful registration!";
        System.out.println("Congratulations,login was successful!");
    }
}

5, Multithreading

1. Concurrency and parallelism

2. Process concept

3. Thread concept

4. Thread scheduling

  • Time sharing scheduling

    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.

    Set thread priority

5. Main thread

package com.itheima.demo05.Thread;

public class Person {
    private String name;

    public void run(){
        //Define the cycle and execute it 20 times
        for(int i=0; i<20; i++){
            System.out.println(name+"-->"+i);
        }
    }

    public Person() {
    }

    public Person(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

package com.itheima.demo05.Thread;
/*
    Main thread: the thread that executes the main method

    Single threaded program: there is only one thread in a java program
    The execution starts with the main method and is executed from top to bottom

    JVM Execute the main method, and the main method will enter the stack memory
    JVM Will find the operating system to open up an execution path from the main method to the cpu
    cpu You can execute the main method through this path
    This path has a name called the main thread
 */
public class Demo01MainThread {
    public static void main(String[] args) {
        Person p1 = new Person("cockroach");
        p1.run();
        System.out.println(0/0);//ArithmeticException: / by zero
        Person p2 = new Person("Wangcai");
        p2.run();
    }
}

6. The first way to create a multithreaded program: create a subclass of Thread class

package com.itheima.demo06.Thread;
//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);
        }
    }
}

package com.itheima.demo06.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 (the 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
 */
public class Demo01Thread {
    public static void main(String[] args) {
        //3. Create subclass objects of Thread class
        MyThread mt = new MyThread();
        //4. Call the start method in the Thread class to start a new Thread and execute the run method
        mt.start();

        for (int i = 0; i <20 ; i++) {
            System.out.println("main:"+i);
        }
    }
}

Topics: Java