JAVA自學筆記(6)—異常、執行緒、函數語言程式設計

轉自:部落格園

作者:YUNNEN

1。異常

1。0 異常的概念

JAVA自學筆記(6)—異常、執行緒、函數語言程式設計

2。throw關鍵字

JAVA自學筆記(6)—異常、執行緒、函數語言程式設計

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(“空指標異常!”);        }        return arc[index];    } }

JAVA自學筆記(6)—異常、執行緒、函數語言程式設計

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(“空指標異常!”);        }        else if(index>=arc。length||index<0)        {            throw new ArrayIndexOutOfBoundsException(“下標超出陣列的範圍!”);        }        return arc[index];    } }

JAVA自學筆記(6)—異常、執行緒、函數語言程式設計

3。Objects 非空判斷

import java。util。Objects; public class Main{    public static void main(String[] args) {        int arc[]=null;        Objects。requireNonNull(arc,“空指標異常”);    }}

4。異常處理的第一種方法 throws關鍵字

JAVA自學筆記(6)—異常、執行緒、函數語言程式設計

import java。io。FileNotFoundException;import java。io。IOException;import java。lang。module。FindException; public class Main {    public static void main(String[] args) throws Exception {        //判斷路徑是否是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(“該路徑不是C:\\。txt”);        }         if(!s。endsWith(“。txt”))             throw new IOException(“檔案字尾不是。txt”);     }}

5。異常處理的第二種方法

try。。。catch()

JAVA自學筆記(6)—異常、執行緒、函數語言程式設計

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(“程式由catch處理”);        }        System。out。println(“後續程式碼”);        //如果丟擲throws 程式交給JVM處理 程式遇到異常就會中斷      }     private static int getelem(int arc[],int index) throws ArrayIndexOutOfBoundsException{        if(index<0||index>=arc。length)        {            throw new ArrayIndexOutOfBoundsException(“下標超出陣列的長度範圍”);        }        return arc[index];    }  }

列印結果:

程式由catch處理後續程式碼

6。Throwable類中常用的方法

JAVA自學筆記(6)—異常、執行緒、函數語言程式設計

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(“後續程式碼”);        //如果丟擲throws 程式交給JVM處理 程式遇到異常就會中斷      }     private static int getelem(int arc[],int index) throws ArrayIndexOutOfBoundsException{        if(index<0||index>=arc。length)        {            throw new ArrayIndexOutOfBoundsException(“下標超出陣列的長度範圍”);        }        return arc[index];    }  }

列印結果:

下標超出陣列的長度範圍java。lang。ArrayIndexOutOfBoundsException: 下標超出陣列的長度範圍java。lang。ArrayIndexOutOfBoundsException: 下標超出陣列的長度範圍後續程式碼java。lang。ArrayIndexOutOfBoundsException: 下標超出陣列的長度範圍at Main。getelem(Main。java:24)at Main。main(Main。java:7)

7。異常處理的注意事項

(1)多個異常物件

import java。util。List;/** 異常處理:多個異常物件的處理* 1、多個異常分別處理* 2、多個異常一次捕獲,多次處理* 3、多個異常一次捕獲一次處理* */ public class Main{    public static void main(String[] args) {        //int []arc=new int[3];        //System。out。println(arc[3]);//ArrayIndexOutOfBoundsException 3        //List list = List。of(4, 3, 26, 6);        //System。out。println(list。get(4));//IndexOutOfBoundsException         /*1。多個異常分別處理        try{            int []arc=new int[3];            System。out。println(arc[3]);        }catch(ArrayIndexOutOfBoundsException e)        {            System。out。println(e);        }         try{            List 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。多個異常一次捕獲多次處理

注意事項 子類物件必須寫在父類物件之上

try{            int []arc=new int[3];            System。out。println(arc[3]);            List 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、多個異常一次捕獲一次處理

try{            int []arc=new int[3];            System。out。println(arc[3]);            List list = List。of(4, 3, 26, 6);            System。out。println(list。get(4));        }         catch(Exception e)         {             System。out。println(e);        }    } */    }    }

(2)finally程式碼塊裡有return語句

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)子父類異常

JAVA自學筆記(6)—異常、執行緒、函數語言程式設計

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(“編譯器異常”);        } catch (Exception e) {            e。printStackTrace();        }    }}

(4)自定義異常類

JAVA自學筆記(6)—異常、執行緒、函數語言程式設計

JAVA自學筆記(6)—異常、執行緒、函數語言程式設計

public class ReadException extends Exception{    public ReadException() {    }     public ReadException(String message) {//新增一個帶異常資訊的構造方法        super(message);    }}

(5)自定義異常的小練習

註冊名稱

import java。util。Scanner; public class Register {    public static String []name={“Mary”,“Lisa”,“Jennie”,“JK”,“Minnie”};//全域性變數    public static void main(String[] args) throws RegisterException {        System。out。println(“請輸入您要註冊的姓名:”);        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(“對不起,您的名字已經被註冊過!”);            }        }        System。out。println(“恭喜您,註冊成功!”);    }}

1)透過throws方法處理異常

import java。util。Scanner; public class Register {    public static String []name={“Mary”,“Lisa”,“Jennie”,“JK”,“Minnie”};//全域性變數    public static void main(String[] args) throws RegisterException {        System。out。println(“請輸入您要註冊的姓名:”);        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(“對不起,您的名字已經被註冊過!”);            }        }        System。out。println(“恭喜您,註冊成功!”);    }}

請輸入您要註冊的姓名:jhfshdbfbsfhe恭喜您,註冊成功!

請輸入您要註冊的姓名:MaryException in thread “main” RegisterException: 對不起,您的名字已經被註冊過!at Register。Checkname(Register。java:16)at Register。main(Register。java:9)

2)try。。。catch()處理

import java。util。Scanner; public class Register {    public static String []name={“Mary”,“Lisa”,“Jennie”,“JK”,“Minnie”};//全域性變數    public static void main(String[] args) {        System。out。println(“請輸入您要註冊的姓名:”);        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(“對不起,您的名字已經被註冊過!”);                } catch (RegisterException e) {                    e。printStackTrace();                    return;                }            }        }        System。out。println(“恭喜您,註冊成功!”);    }}

3)也可以將RegisterException 繼承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”};//全域性變數    public static void main(String[] args) {        System。out。println(“請輸入您要註冊的姓名:”);        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(“對不起,您的名字已經被註冊過!”);            }        }        System。out。println(“恭喜您,註冊成功!”);    }}

2.執行緒

1。0 併發和並行

JAVA自學筆記(6)—異常、執行緒、函數語言程式設計

2。程序與執行緒

JAVA自學筆記(6)—異常、執行緒、函數語言程式設計

執行緒的概念以及對執行緒的分析

JAVA自學筆記(6)—異常、執行緒、函數語言程式設計

3。執行緒的排程

JAVA自學筆記(6)—異常、執行緒、函數語言程式設計

4。主執行緒

JAVA自學筆記(6)—異常、執行緒、函數語言程式設計

5。建立多執行緒程式

第一種建立方式

JAVA自學筆記(6)—異常、執行緒、函數語言程式設計

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

第一次列印結果:

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

第二次列印結果:

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

每次列印結果可能不同 因為多個執行緒併發 搶佔式排程

兩個執行緒 一個main執行緒 一個新執行緒 搶奪CPU(執行時間)

第二種方式

JAVA自學筆記(6)—異常、執行緒、函數語言程式設計

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

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

列印結果:

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

實現Runnable介面建立多執行緒程式的好處

JAVA自學筆記(6)—異常、執行緒、函數語言程式設計

6。Thread類常用方法

(1)獲取執行緒名稱

JAVA自學筆記(6)—異常、執行緒、函數語言程式設計

(2) 設定執行緒的名稱

JAVA自學筆記(6)—異常、執行緒、函數語言程式設計

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

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方法

JAVA自學筆記(6)—異常、執行緒、函數語言程式設計

一秒列印一個數

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。匿名內部類方式實現執行緒的建立

JAVA自學筆記(6)—異常、執行緒、函數語言程式設計

public class Main{    public static void main(String[] args) {        /*第一種建立方式     new Thread(){         @Override         public void run() {             for(int i=1;i<=5;i++)             {                 System。out。println(Thread。currentThread()。getName()+“->”+i);             }         }     }。start();         */         /*第二種透過Runnable介面      (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)簡化版本

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。執行緒安全問題

1。0 概述

JAVA自學筆記(6)—異常、執行緒、函數語言程式設計

2。執行緒安全問題產生

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()+“正在售出第”+ticket+“張票”);                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();    }}

JAVA自學筆記(6)—異常、執行緒、函數語言程式設計

結果中出現 1 0 -1 不存在的票說明 在共享資料的同時發生了安全性問題

3。解決執行緒安全問題

(1)第一種方式 同步程式碼塊

JAVA自學筆記(6)—異常、執行緒、函數語言程式設計

public class Mythread extends Thread {    public Mythread(String name) {        super(name);    }     public Mythread() {    }     @Override    public void run() {        System。out。println(Thread。currentThread()。getName());    }}

同步技術的原理

JAVA自學筆記(6)—異常、執行緒、函數語言程式設計

(2)第二種方法 同步方法

JAVA自學筆記(6)—異常、執行緒、函數語言程式設計

JAVA自學筆記(6)—異常、執行緒、函數語言程式設計

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();            }        }    }}

————靜態同步方法

JAVA自學筆記(6)—異常、執行緒、函數語言程式設計

(3)第三種方式 Lock說

JAVA自學筆記(6)—異常、執行緒、函數語言程式設計

文章太長就先寫到這 ,下一遍繼續!今天也給大家帶來了獨家密的

BATJ

的面試題和相關學習資料,進大廠就從現在開始吧!想獲取這些資料的可以

關注小編,轉發收藏文章

,私信小編【

學習

】來免費獲取吧

JAVA自學筆記(6)—異常、執行緒、函數語言程式設計

BATJ及大廠面試題

JAVA自學筆記(6)—異常、執行緒、函數語言程式設計

JAVA自學筆記(6)—異常、執行緒、函數語言程式設計

JVM系列實戰寶典

JAVA自學筆記(6)—異常、執行緒、函數語言程式設計

名廠面試題

JAVA自學筆記(6)—異常、執行緒、函數語言程式設計

坦克大戰100集系列—23種設計模式

JAVA自學筆記(6)—異常、執行緒、函數語言程式設計

有了這份面試題,自己梳理好,我不信你進不去大廠,想獲取這些資料的可以

關注小編,轉發收藏文章

,私信小編【

學習

】來免費獲取吧!