JAVA self study notes - exception, thread, functional programming

1. Abnormal

1.0 concept of exceptions

 

 

 

2.throw keyword

 

public class Main{
    public static void main(String[] args) {
        int []arc=null;
        getelem(arc,0);
    }

    private static int getelem(int arc[],int index) {
        if(arc==null){
            throw new NullPointerException("Null pointer exception!");
        }
        return arc[index];
    }

}

 

public class Main{
    public static void main(String[] args) {
        int []arc=new int[3];
        getelem(arc,3);
    }

    private static int getelem(int arc[],int index) {
        if(arc==null){
            throw new NullPointerException("Null pointer exception!");
        }
        else if(index>=arc.length||index<0)
        {
            throw new ArrayIndexOutOfBoundsException("Subscript out of range of array!");
        }
        return arc[index];
    }

}

  

3.Objects non empty judgment

 

import java.util.Objects;

public class Main{
    public static void main(String[] args) {
        int arc[]=null;
        Objects.requireNonNull(arc,"Null pointer exception");
    }
}

  

4. The first method of exception handling: throws keyword

import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.module.FindException;

public class Main {
    public static void main(String[] args) throws Exception {
        //Determine whether the path is C: \. TXT
        Filename("C:\\.tx");
    }

    private static void Filename(String s) throws Exception {
        //FileNotFoundException extends IOException extends Exception
        if(!s.equals("C:\\.txt")){
            throw new FileNotFoundException("The path is not C:\\.txt");
        }
         if(!s.endsWith(".txt"))
             throw new IOException("File suffix is not.txt");

    }
}

5. The second method of exception handling

try...catch()

 

import java.lang.invoke.MethodHandles;

public class Main{
    public static void main(String[] args) {
        int[] arc=new int[3];
        try {
            int getelem = getelem(arc, 3);
        }catch(ArrayIndexOutOfBoundsException e)
        {
            System.out.println("Procedure by catch handle");
        }
        System.out.println("Subsequent code");
        //If the throws program is passed to the JVM handler, it will break if it encounters an exception


    }

    private static int getelem(int arc[],int index) throws ArrayIndexOutOfBoundsException{
        if(index<0||index>=arc.length)
        {
            throw new ArrayIndexOutOfBoundsException("Subscript out of range of array length");
        }
        return arc[index];
    }


}

Print results:

Program is handled by catch
Subsequent code

 

6. Common methods in throwable class

import java.lang.invoke.MethodHandles;

public class Main{
    public static void main(String[] args) {
        int[] arc=new int[3];
        try {
            int getelem = getelem(arc, 3);
        }catch(ArrayIndexOutOfBoundsException e)
        {
            System.out.println(e.getMessage());
            System.out.println(e.toString());
            System.out.println(e);
            e.printStackTrace();
        }
        System.out.println("Subsequent code");
        //If the throws program is passed to the JVM handler, it will break if it encounters an exception


    }

    private static int getelem(int arc[],int index) throws ArrayIndexOutOfBoundsException{
        if(index<0||index>=arc.length)
        {
            throw new ArrayIndexOutOfBoundsException("Subscript out of range of array length");
        }
        return arc[index];
    }


}

  

Print results:

Subscript out of range of array length
java.lang.ArrayIndexOutOfBoundsException : subscript out of array length range
java.lang.ArrayIndexOutOfBoundsException : subscript out of array length range
Subsequent code
java.lang.ArrayIndexOutOfBoundsException : subscript out of array length range
at Main.getelem(Main.java:24)
at Main.main(Main.java:7)

7. Precautions for exception handling

(1) Multiple exception objects

import java.util.List;
/*
* Exception handling: handling of multiple exception objects
* 1,Handle multiple exceptions separately
* 2,Multiple exceptions caught at one time and handled multiple times
* 3,Multiple exceptions are caught and handled once at a time
* */

public class Main{
    public static void main(String[] args) {
        //int []arc=new int[3];
        //System.out.println(arc[3]);//ArrayIndexOutOfBoundsException 3
        //List<Integer> list = List.of(4, 3, 26, 6);
        //System.out.println(list.get(4));//IndexOutOfBoundsException

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

        try{
            List<Integer> list = List.of(4, 3, 26, 6);
            System.out.println(list.get(4));
        }catch(IndexOutOfBoundsException e)
        {
            System.out.println(e);
        }

        java.lang.ArrayIndexOutOfBoundsException: 3
        java.lang.IndexOutOfBoundsException: Index 4 out-of-bounds for length 4

      */

        /*
        2.Multiple exceptions caught at one time and handled multiple times
        Note that subclass objects must be written on top of parent objects
        try{
            int []arc=new int[3];
            System.out.println(arc[3]);
            List<Integer> list = List.of(4, 3, 26, 6);
            System.out.println(list.get(4));
        }
        catch(ArrayIndexOutOfBoundsException e){
            System.out.println(e);
        }
        catch (IndexOutOfBoundsException e)
        {
            System.out.println(e);
        }
    }
      */

        /*
        3,Multiple exceptions are caught and handled once at a time
       try{
            int []arc=new int[3];
            System.out.println(arc[3]);
            List<Integer> list = List.of(4, 3, 26, 6);
            System.out.println(list.get(4));
        }
         catch(Exception e)
         {
             System.out.println(e);
        }
    }
 */
    } 
    }

(2) return statement in finally code block

public class Main{
    public static void main(String[] args) {
        int method = method();
        System.out.println(method);//20

    }

    private static int method() {
        try{
            int a[]=null;
            int sum=0;
            return sum;
        }catch(NullPointerException e)
        {
            System.out.println(e);
        }
        finally {
            int sum=20;
            return sum;
        }
    }
}

(3) Child parent exception

public class FU {
    public void show1() throws NullPointerException, ClassCastException { }
    public void show2() throws IndexOutOfBoundsException { };
    public void show3() throws IndexOutOfBoundsException { };

    public void show4() { }
}
class ZI extends FU{
    @Override
    public void show1() throws NullPointerException, ClassCastException { }
    public void show2() throws ArrayIndexOutOfBoundsException{}

    @Override
    public void show3(){}
    public void show4(){
        try {
            throw  new Exception("Compiler exception");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

(4) Custom exception class

 

 

public class ReadException extends Exception{
    public ReadException() {
    }

    public ReadException(String message) {//Add a construction method with exception information
        super(message);
    }
}

(5) Custom exception exercises

Registered name

public class RegisterException extends Exception {
    public RegisterException(String message) {
        super(message);
    }

    public RegisterException() {
    }
}

1) Handling exceptions with throws method

 

import java.util.Scanner;

public class Register {
    public static String []name={"Mary","Lisa","Jennie","JK","Minnie"};//global variable
    public static void main(String[] args) throws RegisterException {
        System.out.println("Please enter the name you want to register:");
        Scanner input=new Scanner(System.in);
        String usename=input.next();
        Checkname(usename);

    }
    public static void Checkname(String usename) throws RegisterException {
        for (String s : name) {
            if(s.equals(usename))//true
            {
                throw new RegisterException("Sorry, your name has been registered!");
            }
        }
        System.out.println("Congratulations on your successful registration!");
    }
}

 

Please enter the name you want to register:
jhfshdbfbsfhe
Congratulations on your successful registration!

 

Please enter the name you want to register:
Mary
Exception in thread "main" RegisterException: sorry, your name has been registered!
at Register.Checkname(Register.java:16)
at Register.main(Register.java:9)

2) try...catch() processing

import java.util.Scanner;

public class Register {
    public static String []name={"Mary","Lisa","Jennie","JK","Minnie"};//global variable
    public static void main(String[] args) {
        System.out.println("Please enter the name you want to register:");
        Scanner input=new Scanner(System.in);
        String usename=input.next();
        Checkname(usename);

    }
    public static void Checkname(String usename){
        for (String s : name) {
            if(s.equals(usename))//true
            {
                try {
                    throw new RegisterException("Sorry, your name has been registered!");
                } catch (RegisterException e) {
                    e.printStackTrace();
                    return;
                }
            }
        }
        System.out.println("Congratulations on your successful registration!");
    }
}

 

3) You can also inherit RegisterException from RuntimeException

 

public class RegisterException extends RuntimeException {
    public RegisterException(String message) {
        super(message);
    }

    public RegisterException() {
    }
}

  

import java.util.Scanner;

public class Register {
    public static String []name={"Mary","Lisa","Jennie","JK","Minnie"};//global variable
    public static void main(String[] args) {
        System.out.println("Please enter the name you want to register:");
        Scanner input=new Scanner(System.in);
        String usename=input.next();
        Checkname(usename);

    }
    public static void Checkname(String usename){
        for (String s : name) {
            if(s.equals(usename))//true
            {
                throw new RegisterException("Sorry, your name has been registered!");
            }
        }
        System.out.println("Congratulations on your successful registration!");
    }
}

2. Thread

1.0 concurrent and parallel

2. Process and thread

 

 

 

The concept of thread and its analysis

 

 

3. Scheduling of threads

4. Main thread

 

5. Create a multithreaded program

The first way to create

 

 

public class Mythread extends Thread {
    @Override
    public void run() {
        for(int i=0;i<5;i++)
        {
            System.out.println("run:"+i);
        }
    }
}

  

public class Main{
    public static void main(String[] args) {
        Mythread mt=new Mythread();
        mt.start();
        for(int i=0;i<5;i++)
        {
            System.out.println("Main:"+i);
        }
    }
}

 

 

First printing result:

Main:0
Main:1
run:0
Main:2
Main:3
run:1
Main:4
run:2
run:3
run:4

 

Second printing result:

Main:0
run:0
Main:1
run:1
Main:2
run:2
Main:3
run:3
Main:4
run:4

The results of each printing may be different because of concurrent preemptive scheduling of multiple threads

Two threads, one main thread and one new thread seize CPU (execution time)

The second way

public class RunnableImpl implements Runnable{
    @Override
    public void run() {
        for(int i=0;i<5;i++)
        {
            System.out.println(Thread.currentThread().getName()+"--->"+i);
        }
    }
}
public class Main{
    public static void main(String[] args) {
     RunnableImpl impl=new RunnableImpl();
     Thread t=new Thread(impl);
     t.start();
     for(int i=0;i<5;i++)
     {
         System.out.println(Thread.currentThread().getName()+"--->"+i);
     }
    }
}

 

Print results:

main--->0
main--->1
Thread-0--->0
main--->2
Thread-0--->1
Thread-0--->2
main--->3
Thread-0--->3
main--->4
Thread-0--->4

 

The advantage of realizing Runnable interface to create multithreaded program

 

6. Common methods of thread class

(1) Get thread name

(2) Set the name of the thread

 

public class Mythread extends Thread {
    public Mythread(String name) {
        super(name);
    }

    public Mythread() {
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}

  

public  class Main{
    public static void main(String[] args) {
        Mythread mt=new Mythread();
        mt.setName("START");//START
        mt.start();


        new Mythread("Hello").start();//Hello

    }
}

(3) sleep method

 

Print one number per second

 

public class Main{
    public static void main(String[] args) {
        for (int i = 1; i <=10 ; i++) {
            System.out.println(i);
            try{
                Thread.sleep(1000);
            }catch(InterruptedException e)
            {
                e.printStackTrace();
            }
        }
    }
}

7. Anonymous inner class method to create threads

 

public class Main{
    public static void main(String[] args) {
        /*The first way to create
     new Thread(){
         @Override
         public void run() {
             for(int i=1;i<=5;i++)
             {
                 System.out.println(Thread.currentThread().getName()+"->"+i);
             }
         }
     }.start();
         */

        /*The second is through the Runnable interface
      (1)
        Runnable r=new Runnable() {
            @Override
            public void run() {
                for(int i=1;i<=5;i++)
                {
                    System.out.println(Thread.currentThread().getName()+"->"+i);
                }
            }
        };
        new Thread(r).start();




        (2)Simplified version
            new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i=1;i<=5;i++)
                {
                    System.out.println(Thread.currentThread().getName()+"->"+i);
                }
            }
        }).start();
        */
        for(int i=1;i<=5;i++)
        {
            System.out.println(Thread.currentThread().getName()+"->"+i);
        }
    }
}

 

3. Thread safety

1.0 general

2. Thread safety problems

public class RunnableImpl implements Runnable{
    private int ticket=100;
    @Override
    public void run() {
      while(true)
        {
            if(ticket>0)
            {
                try{
                    Thread.sleep(100);
                }catch(Exception e)
                {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+"Selling No"+ticket+"Tickets");
                ticket--;
            }
        }
    }
}

  

public class Main{
    public static void main(String[] args) {
    RunnableImpl r=new RunnableImpl();
    Thread r1=new Thread(r);
    Thread r2=new Thread(r);
    Thread r3=new Thread(r);
    r1.start();
    r2.start();
    r3.start();
    }
}

The result shows that there is a security problem at the same time of data sharing

3. Solve thread safety problems

(1) The first way to synchronize code blocks

public class RunnableImpl implements Runnable{
    private int ticket=100;
    Object obj=new Object() ;
    @Override
    public void run() {
      while(true)
        {
            synchronized (obj)
        {
            if(ticket>0)
            {
                try{
                    Thread.sleep(100);
                }catch(Exception e)
                {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+"Selling No"+ticket+"Tickets");
                ticket--;
            }
        }
        }
    }
}

 

Principle of synchronous technology

 

 

(2) Second method synchronization method

 

 

public class RunnableImpl implements Runnable{
    private int ticket=100;
    @Override
    public void run() {
      while(true)
        {
        payticket();
    }
    }
    public synchronized void payticket()
    {
        if(ticket>0)
        {
            try{
                Thread.sleep(100);
            }catch(Exception e)
            {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"Selling No"+ticket+"Tickets");
            ticket--;
        }
    }
    }

------ static synchronization method

 

(3) The third way Lock

 

 

Style 1:

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class RunnableImpl implements Runnable{
    private int ticket=100;
    Lock l=new ReentrantLock();
    @Override
    public void run() {
        while (true)
        {
            l.lock();
            if(ticket>0)
            {
                try{
                    Thread.sleep(100);
                }catch(Exception e)
                {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+"Selling No"+ticket+"Tickets");
                ticket--;
            }
            l.unlock();
        }
    }
}

 

Writing method II (high efficiency)

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class RunnableImpl implements Runnable{
    private int ticket=100;
    Lock l=new ReentrantLock();
    @Override
    public void run() {
        while (true)
        {
            l.lock();
            if(ticket>0)
            {
                try{
                    Thread.sleep(100);
                    System.out.println(Thread.currentThread().getName()+"Selling No"+ticket+"Tickets");
                    ticket--;
                }catch(Exception e)
                {
                    e.printStackTrace();
                }finally {
                    l.unlock();
                }

            }

        }
    }
}

  

4. Thread status

1.0 general

2.0 waiting to wake up cases

Analyze the case of selling steamed buns

 

code implementation

 

 

 

public class Sale {
    public static void main(String[] args) {
        Object obj=new Object();//Lock object
        //customer
        new Thread() {
            @Override
            public void run() {
                synchronized (obj)
                {
                    System.out.println("Customers tell their boss what they need");
                    try {
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("Delicious steamed buns are ready to eat!");
            }
        }.start();

        //boss

        new Thread(){
            @Override
            public void run() {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (obj)
                { 
                    System.out.println("Boss made the bun in 5 seconds");
                    obj.notify();
                }
            }
        }.start();
    }
}

  

Print results:

Customers tell their boss what they need
Boss made the bun in 5 seconds
Delicious steamed buns are ready to eat!

 

wait with parameter method and notify method in Object class

 

 

 

3. Waiting for wake-up mechanism

case

 

 

public class Baozi {
   String Pi;
   String Xian;
   boolean falg=false;
}

  

public class Baozipu extends Thread {
   private Baozi baozi;
    public Baozipu( Baozi baozi) {
        this.baozi = baozi;
    }
    @Override
    public void run() {
        int count=0;
        while(true)
        {
            synchronized (baozi)
            {
                //The state of baozi is
                if(baozi.falg==true)
                {
                    try {
                        baozi.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //Production of baozi
                if(count%2==0)
                {
                    baozi.Pi="Thin skin";
                    baozi.Xian="Pork and corn";
                }
                else
                {
                    baozi.Pi="Cold Rice Noodles";
                    baozi.Xian="Three delicacies of beef";
                }
                count++;
                System.out.println("Doing"+baozi.Pi+baozi.Xian+"Baozi of");

                try {
                    Thread.sleep(5000);//5 seconds production
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                baozi.falg=true;
                baozi.notify();
                System.out.println(baozi.Pi+baozi.Xian+"The steamed buns are ready to be eaten!");
            }
        }

    }
}

 

 

 

public class Chihuo extends Thread {
    private Baozi baozi;

    public Chihuo(Baozi baozi) {
        this.baozi = baozi;
    }

    @Override
    public void run() {
        while(true)
        {
            synchronized (baozi)
            {
                if(baozi.falg==false)
                {
                    try {
                        baozi.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                //After awakening

                System.out.println("Food in progress:"+baozi.Pi+baozi.Xian+"Baozi of");
                baozi.falg=false;
                baozi.notify();
                System.out.println("The food has been eaten and production continues");
                System.out.println("----------------------");
            }
        }

    }
}

  

 

Test (customer)

public class Main{
    public static void main(String[] args) {
     Baozi bz=new Baozi();
     new Baozipu(bz).start();
     new Chihuo(bz).start();
    }
}

 

5. Thread pool

 

public class RunnableImpl implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"Executing");
    }
}

  

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main{
    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(2);
        pool.submit(new RunnableImpl());//pool-1-thread-1 executing
        pool.submit(new RunnableImpl());//pool-1-thread-2 executing
        //Only two thread pools will be open all the time, and one thread can be returned for further use after the end of the pool
        pool.submit(new RunnableImpl());//pool-1-thread-1 executing


        pool.shutdown();//Destroy thread pool
    }
}

  

6. Functional programming idea

1.0 general

 

2.0 experience Lambda better

 

 

public class Main{
    public static void main(String[] args) {
        new Thread() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "Executing");
            }
        }.start();


        System.out.println("----------");

        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "Executing");
        }).start();
    }
}

 

Print results:

----------
Thread-1 is executing
Thread-0 is executing

3.0 Lambda standard format

(1) No parameter no return value

public interface Cook {
    public abstract void makefood();
}

  

public class Main{
    public static void main(String[] args) {
    show(()->{
            System.out.println("time to have a meal! Virtue and goodness");
        }
        );
    }

    public  static void show(Cook cook) {
     cook.makefood();
    }
}

 

Print results:

time to have a meal! Virtue and goodness

(2) There are parameters and return values

Sort age

import java.util.Arrays;
import java.util.Comparator;

public class Main{
    public static void main(String[] args) {
        Person[] person = {new Person("V", 25),
                new Person("JK", 23),
                new Person("Jin", 27)};
        /*
        Arrays.sort(person, new Comparator<Person>() {
            @Override
            public int compare(Person o1, Person o2) {
              return o1.getAge()-o2.getAge();//Ascending order
            }
        });
        */

        Arrays.sort(person,(Person o1, Person o2) ->
        {
            return o1.getAge()-o2.getAge();
        });

        for (Person person1 : person) {
            System.out.println(person1.getName()+" "+person1.getAge());
        }
    }
}

  

Print results:

JK 23
V 25
Jin 27

 

 

4.0 lambda can be omitted

Tags: Java Lambda jvm Programming

Posted on Thu, 18 Jun 2020 04:19:38 -0400 by Nuser