Summary of Java core programming (IV. exceptions and threads), senior Java Architect of Netease

Posted by Saphod on Wed, 15 Dec 2021 00:06:14 +0100

1.3 default mechanism for exception generation and handling

The default processing process for exception generation is parsing (you can understand it):

  1. By default, an exception object, ArithmeticException, will be automatically created in the exception code

  2. The exception will be thrown to the caller from the point in the method, and the caller will eventually throw it to the JVM virtual machine

  3. After the virtual machine receives the exception object, the console now directly outputs the exception stack information data.

  4. Kill the current program directly from the currently executed exception point.

  5. The subsequent code has no chance to execute because the program has died

The default exception handling mechanism is not good. Once an exception occurs, the program will die immediately

1.3 handling of compile time exceptions

Method 1: throw an exception

Format:

method throws Exception{

    

}



  • Where compile time exceptions occur, the exceptions are thrown to the caller layer by layer, and the caller finally throws them to the JVM virtual machine. The JVM virtual machine outputs exception information and directly kills the program. This method is the same as the default method. Although it can solve the errors during code compilation, once there is an exception at runtime, the program will still die immediately. This method is not good

Method 2: capture processing: handle the exception by yourself, and who appears will handle it

Format:

try{

    // Monitor code with possible exceptions

}catch{Exception type 1 variable}{

    // Handling exceptions

}catch{Exception type 2 variable}{

    // Handling exceptions

}



  • The second method can handle exceptions, and the code will not die after exceptions. However, theoretically, this method is not the best. The upper callers can't directly know the execution of the lower layer!

Method 3: throw the exception layer by layer to the outermost caller where the exception occurs, and the outermost caller will capture and process it centrally

try{

    // Possible exception codes

}catch(Exception e){

    e.printStackTrae(); //Print exception stack information directly

}



  • In this scheme, the outermost caller can know the underlying execution, and the program will not die immediately after an exception, which is the best scheme in theory.

  • Although there are three ways to deal with exceptions, each way can be used as long as it can solve your problems in development!

1.4 finally keyword

  • It is used in the exception format of capture and processing, which is placed at the end

  • try{
    
        //Possible abnormal code!
    
    }catch{Exception e}{
    
        e.printStackTrace();
    
    }finally{
    
        // Whether the code is abnormal or executed normally, the code here must be executed in the end!!
    
    }
    
    
    
    
  • finally: you can release resources after code execution

  • All resources implement the Closeable interface and have their own close() closing method

  • try: 1 occurrence

  • Catch: occurs 0 - N times (if finally, then catch can not)

  • finally: 0 - 1 occurrences

1.5 custom exception (understand)

Java has designed a class to represent all possible exceptions in development, but in actual development, there may be countless exceptions. Java cannot define a class for all exceptions in the world. If an enterprise wants to define an exception for a certain business problem, it needs to define its own exception class.

1.4 multithreading (concurrent programming)

  1. What is a process?

    A: the program is static, and the running program is a process

  2. Three characteristics of process

    • Independence: processes are independent of each other and have their own independent memory areas

    • Dynamic: a process is a running program that dynamically occupies memory, CPU, network and other resources

    • Concurrency: the CPU will poll and switch time-sharing to serve each process in turn, because the switching speed is very fast, which makes us feel like executing at the same time. This is concurrency

      • Concurrency: multiple are executing at the same time
  3. What is a thread?

    A: threads belong to processes. A process can contain multiple threads, which is multithreading

1.5 thread creation method

Multithreading is very useful. There are three ways to create threads in the process:

1.5. 1 inherit Thread class

How to inherit Thread class:

  1. Define a Thread class that inherits the Thread class

  2. Override the run() method

  3. Create a new thread object

    Thread t = new MyThread();
    
    
    
    
  4. Call the start() method of the thread object to start the thread

public class ThreadDemo {

    // The started ThreadDemo is treated as a process.

    // The main method is executed by the main thread. It is understood that the main method is a main thread

    public static void main(String[] args) {

        // 3. Create a thread object

        Thread t = new MyThread();

        // 4. Call the start() method of the thread object to start the thread, and finally execute the run() method!

        t.start();

        

        

        for(int i = 0 ; i < 100 ; i++ ){

            System.out.println("main Thread output:"+i);

        }

    }

}



// 1. Define a Thread class to inherit the Thread class.

class MyThread extends Thread{

    // 2. Rewrite the run() method

    @Override

    public void run() {

        // The execution method of the thread.

        for(int i = 0 ; i < 100 ; i++ ){

            System.out.println("Child thread output:"+i);

        }

    }

}



1.5. 2. Implement Runnable interface

  1. Create a thread task class to implement the Runnable interface

  2. Override the run() method

  3. Create a thread task object (Note: the thread task object is not a thread object, but the object that executes the task of the thread)

    Runnable target = new MyRunnable();
    
    
    
    
  4. Wrap the thread task object into a thread object, and you can specify the thread name

    // Thread t = new Thread(target);
    
    Thread t = new Thread(target,"1 Thread No");
    
    
    
    
  5. Call the start() method of the thread object to start the thread

public class ThreadDemo {

    public static void main(String[] args) {

        // 3. Create a thread task object (Note: the thread task object is not a thread object, but only the object that executes the task of the thread)

        Runnable target = new MyRunnable();

        // 4. Wrap the thread task object into a thread object And the thread name can be specified

        // Thread t = new Thread(target);

        Thread t = new Thread(target,"1 Thread No");

        // 5. Call the start() method of the thread object to start the thread

        t.start();



        Thread t2 = new Thread(target);

        // Call the start() method of the thread object to start the thread

        t2.start();



        for(int i = 0 ; i < 10 ; i++ ){

            System.out.println(Thread.currentThread().getName()+"==>"+i);

        }

    }

}



// 1. Create a thread task class to implement the Runnable interface.

class MyRunnable implements Runnable{

    // 2. Rewrite the run() method

    @Override

    public void run() {

        for(int i = 0 ; i < 10 ; i++ ){

            System.out.println(Thread.currentThread().getName()+"==>"+i);

        }

    }

}



1.5. 2.1 constructor of thread

  • public Thread(){}

  • public Thread(String name){}

  • public Thread(Runnable target) {}: assign a new Thread object

  • public Thread(Runnable target,String name): assign a new Thread object and specify a new Thread name

1.5. 2.1 advantages and disadvantages

Disadvantages: the code is a little more complex

advantage:

  • The thread task class only implements the Runnable interface, and can continue to inherit other classes, and can continue to implement other interfaces (to avoid the limitations of Le Dan inheritance)

  • The same thread task object can be wrapped into multiple thread objects

1.5. 3. Implement Callable interface

  1. Define a thread task class to implement the Callable interface and declare the result type returned by the thread

  2. Override the call method of the thread task class, which can directly return the execution result

  3. Create a Callable thread task object

  4. Wrap the Callable thread task object into a future task object

  5. Wrap the future task object into a thread object

  6. Call the thread's start() method to start the thread

public class ThreadDemo {

    public static void main(String[] args) {

        // 3. Create a Callable thread task object

        Callable call = new MyCallable();

        // 4. Wrap the Callable task object into a future task object

        //      -- public FutureTask(Callable<V> callable)

        // What is the target of the future mission and what is its use?

        //      --The future task object is actually a Runnable object: in this way, it can be packaged as a thread object!

        //      --Future task objects can get the results of thread execution after thread execution.

        FutureTask<String> task = new FutureTask<>(call);

        // 5. Wrap the future task object into a thread object

        Thread t = new Thread(task);

        // 6. Start thread object

        t.start();



        for(int i = 1 ; i <= 10 ; i++ ){

            System.out.println(Thread.currentThread().getName()+" => " + i);

        }



        // Finally, get the result of thread execution. If the thread has no result, give up the CPU to get the result after the thread is executed

        try {

            String rs = task.get(); // Get the result returned by the call method (normal / abnormal result)

            System.out.println(rs);

        }  catch (Exception e) {

            e.printStackTrace();

        }



    }

}



// 1. Create a thread task class to implement the Callable interface and declare the result type returned by the thread

class MyCallable implements Callable<String>{

    // 2. Rewrite the call method of the thread task class!

    @Override

    public String call() throws Exception {

        // Requirements: calculate the sum and return of 1-10

        int sum = 0 ;

        for(int i = 1 ; i <= 10 ; i++ ){

            System.out.println(Thread.currentThread().getName()+" => " + i);

            sum+=i;

        }

        return Thread.currentThread().getName()+"The results of the implementation are:"+sum;

    }

}



1.5. 4 advantages and disadvantages

Advantages: all advantages

1.6 common API s for threads

API of Thread class

  1. public void setName(String name): name the current thread

  2. public void getName(): get the name of the current thread

    • The Thread has a default name. The default name of the child Thread is: Thread - index

    • The default name of the main thread is: main

  3. public static Thread currentThread(): get the current thread object. You can get the thread object in which thread the code is in

  4. public static void sleep(long time): how many milliseconds does the current thread sleep before continuing execution

  5. public Thread(String name): create an object and name it

public class ThreadDemo {

    // The started ThreadDemo is treated as a process.

    // The main method is executed by the main thread. It is understood that the main method is a main thread

    public static void main(String[] args) {

        // Create a thread object

        Thread t1 = new MyThread();

        t1.setName("1 Thread No");

        t1.start();

        //System.out.println(t1.getName()); //  Get thread name



        Thread t2 = new MyThread();

        t2.setName("2 Thread No");

        t2.start();

        //System.out.println(t2.getName());  //  Get thread name



        // How to get the name of the main thread?

        // This code gets the thread object in which thread.

        Thread m = Thread.currentThread();

        m.setName("Strongest thread main");

        //System.out.println(m.getName()); //  Get thread name



        for(int i = 0 ; i < 10 ; i++ ){

            System.out.println(m.getName()+"==>"+i);

        }

    }

}



// 1. Define a Thread class to inherit the Thread class.

class MyThread extends Thread{

    // 2. Rewrite the run() method

    @Override

    public void run() {

        // The execution method of the thread.

        for(int i = 0 ; i < 10 ; i++ ){


# summary

Opportunities are reserved for those who are prepared. Before applying for a job, everyone should clarify their attitude, be familiar with the job search process, be fully prepared and do some predictable things well.

For fresh graduates, school recruitment is more suitable for you, because most of them will not have work experience, and enterprises will not have the demand for work experience. At the same time, you don't need to fake the actual combat experience in order to make your resume stand out, but it will make the interviewer suspicious.

You should be clear about your development direction in college. If you are a freshman, you should make sure you want to be a teacher in the future Java Engineers, don't spend too much time learning other technical languages, advanced mathematics and so on. It's better to think about how to consolidate Java Basics. The following figure covers what new students and even Xiao Bai who has changed careers need to learn Java Content:

**You need to get this learning plan route and the information mentioned in the article Java Ali internal Java Students of this year's employment dictionary, please forward this article for support and pay attention to me**

**[CodeChina Open source project: [first tier big factory] Java Analysis of interview questions+Core summary learning notes+Latest explanation Video]](https://codechina.csdn.net/m0_60958482/java-p7)**

![](https://img-blog.csdnimg.cn/img_convert/02c18b75c2a584cdeecdc513d02b2912.png)

   }

    }

}



// 1. Define a Thread class to inherit the Thread class.

class MyThread extends Thread{

    // 2. Rewrite the run() method

    @Override

    public void run() {

        // The execution method of the thread.

        for(int i = 0 ; i < 10 ; i++ ){


# summary

Opportunities are reserved for those who are prepared. Before applying for a job, everyone should clarify their attitude, be familiar with the job search process, be fully prepared and do some predictable things well.

For fresh graduates, school recruitment is more suitable for you, because most of them will not have work experience, and enterprises will not have the demand for work experience. At the same time, you don't need to fake the actual combat experience in order to make your resume stand out, but it will make the interviewer suspicious.

You should be clear about your development direction in college. If you are a freshman, you should make sure you want to be a teacher in the future Java Engineers, don't spend too much time learning other technical languages, advanced mathematics and so on. It's better to think about how to consolidate Java Basics. The following figure covers what new students and even Xiao Bai who has changed careers need to learn Java Content:

**You need to get this learning plan route and the information mentioned in the article Java Ali internal Java Students of this year's employment dictionary, please forward this article for support and pay attention to me**

**[CodeChina Open source project: [first tier big factory] Java Analysis of interview questions+Core summary learning notes+Latest explanation Video]](https://codechina.csdn.net/m0_60958482/java-p7)**

[External chain picture transfer...(img-Lan1RDdV-1630902971897)]

![](https://img-blog.csdnimg.cn/img_convert/b49693fb56c3efcdf2cdf7b3b5cfbca4.png)

Topics: Java Spring Back-end Programmer