JAVA高級編程開發技巧

一、多線程

1、線程的創建、啟動、停止、休眠、等待

public class ThreadDemo extends Thread {

    public void run(){
        System.out.println("線程的執行");
    }

    public static void main(String[] args){
        ThreadDemo thread = new ThreadDemo();
        thread.start(); // 啟動線程
    }
}

2、線程池的使用

public class ThreadPoolDemo {

    public static void main(String[] args){
        ExecutorService executorService = Executors.newFixedThreadPool(5); // 創建固定大小的線程池
        for(int i=0; i<10; i++){
            executorService.execute(new Runnable() {
                public void run() {
                    System.out.println(Thread.currentThread().getName() + "正在執行任務");
                }
            });
        }
        executorService.shutdown(); // 關閉線程池
    }
}

3、線程間的通信

public class ThreadCommunicationDemo {

    public static void main(String[] args) {
        final Business business = new Business();
        new Thread(new Runnable() {
            public void run() {
                for(int i=0; i<50; i++){
                    business.sub();
                }
            }
        }).start();

        for(int i=0; i<50; i++){
            business.main();
        }

    }

    static class Business{
        private boolean flag = true;

        public synchronized void main(){
            if(flag){
                try {
                    this.wait(); // 如果flag為true,則等待
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            for(int i=0; i<5; i++){
                System.out.println(Thread.currentThread().getName() + "運行第" + i + "次");
            }
            flag = true; // 設置flag為true
            this.notify(); // 通知
        }

        public synchronized void sub(){
            if(!flag){
                try {
                    this.wait(); // 如果flag為false,則等待
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            for(int i=0; i<10; i++){
                System.out.println(Thread.currentThread().getName() + "運行第" + i + "次");
            }
            flag = false; // 設置flag為false
            this.notify(); // 通知
        }
    }
}

二、異常處理

1、try-catch-finally語句塊

public class TryCatchFinallyDemo {

    public static void main(String[] args){
        try {
            int i = 1 / 0;
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            System.out.println("finally語句塊");
        }
    }
}

2、自定義異常類

public class CustomExceptionDemo {

    public static void main(String[] args) throws CustomException{
        int age = 10;
        if(age < 18){
            throw new CustomException("未滿18周歲,無法註冊");
        } else {
            System.out.println("註冊成功");
        }
    }
}

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

3、finally語句塊中的return語句

public class FinallyReturnDemo {

    public static void main(String[] args) {
        System.out.println(getNum());
    }

    public static int getNum(){
        try {
            return 1;
        } finally{
            return 2;
        }
    }
}

三、泛型

1、泛型類、泛型方法

public class GenericDemo {

    private T t;

    public void setT(T t) {
        this.t = t;
    }

    public T getT() {
        return t;
    }

    public  void printMsg(E e){
        System.out.println(e.getClass());
    }

    public static void main(String[] args){
        GenericDemo genericDemo = new GenericDemo();
        genericDemo.setT("JAVA高級編程開發技巧");
        System.out.println(genericDemo.getT());

        genericDemo.printMsg("泛型方法"); // 輸出java.lang.String

        GenericDemo genericDemo1 = new GenericDemo();
        genericDemo1.setT(2019);
        System.out.println(genericDemo1.getT());

        genericDemo1.printMsg(123); // 輸出java.lang.Integer
    }
}

2、泛型接口

public interface GenericInterface {

    public void setT(T t);

    public T getT();

    public void printMsg(String msg);
}

class GenericImpl implements GenericInterface{

    private T t;

    public void setT(T t) {
        this.t = t;
    }

    public T getT() {
        return t;
    }

    public void printMsg(String msg) {
        System.out.println(msg + ":" + t);
    }

    public static void main(String[] args){
        GenericInterface genericInterface = new GenericImpl();
        genericInterface.setT("泛型接口");
        System.out.println(genericInterface.getT());

        genericInterface.printMsg("JAVA高級編程開發技巧");
    }
}

四、註解

1、自定義註解

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {

    public String value() default "自定義註解";
}

@MyAnnotation
public class AnnotationDemo {

    public static void main(String[] args){
        Annotation[] annotations = AnnotationDemo.class.getAnnotations();
        for(Annotation annotation : annotations){
            if(annotation instanceof MyAnnotation){
                MyAnnotation myAnnotation = (MyAnnotation) annotation;
                System.out.println(myAnnotation.value()); // 輸出自定義註解
            }
        }
    }
}

2、元註解

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface MyAnnotation {

    public String value() default "元註解";
}

@MyAnnotation
public class AnnotationDemo {

    public static void main(String[] args){
        Annotation[] annotations = AnnotationDemo.class.getAnnotations();
        for(Annotation annotation : annotations){
            if(annotation instanceof MyAnnotation){
                MyAnnotation myAnnotation = (MyAnnotation) annotation;
                System.out.println(myAnnotation.value()); // 輸出元註解
            }
        }
    }
}

五、高級特性

1、反射機制

public class ReflectionDemo {

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        // 獲取類的Class對象
        Class clazz = Class.forName("com.reflection.Test");
        Object object = clazz.newInstance();

        // 獲取類的構造方法
        Constructor constructor = clazz.getDeclaredConstructor();
        constructor.setAccessible(true);
        Object object1 = constructor.newInstance();

        // 獲取類的私有方法
        Method method = clazz.getDeclaredMethod("privateMethod", String.class);
        method.setAccessible(true);
        method.invoke(object, "JAVA高級編程開發技巧");

        // 獲取類的字段
        Field field = clazz.getDeclaredField("name");
        field.setAccessible(true);
        field.set(object1, "reflnation");
        System.out.println(field.get(object1));
    }
}

class Test {
    private String name;

    public Test(){
        this.name = "Java";
    }

    private void privateMethod(String msg){
        System.out.println("私有方法:" + msg);
    }
}

2、動態代理

public interface Service {

    public void add();

    public void update();
}

public class ServiceImpl implements Service{

    public void add() {
        System.out.println("添加用戶");
    }

    public void update() {
        System.out.println("修改用戶");
    }
}

public class ProxyDemo {

    public static void main(String[] args) {
        Service service = new ServiceImpl();
        Service proxy = (Service) Proxy.newProxyInstance(service.getClass().getClassLoader(), service.getClass().getInterfaces(), new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println(method.getName() + "開始執行");
                Object result = method.invoke(service, args);
                System.out.println(method.getName() + "執行完成");
                return result;
            }
        });
        proxy.add();
        proxy.update();
    }
}

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/312948.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2025-01-06 15:17
下一篇 2025-01-06 15:17

相關推薦

  • Java JsonPath 效率優化指南

    本篇文章將深入探討Java JsonPath的效率問題,並提供一些優化方案。 一、JsonPath 簡介 JsonPath是一個可用於從JSON數據中獲取信息的庫。它提供了一種DS…

    編程 2025-04-29
  • java client.getacsresponse 編譯報錯解決方法

    java client.getacsresponse 編譯報錯是Java編程過程中常見的錯誤,常見的原因是代碼的語法錯誤、類庫依賴問題和編譯環境的配置問題。下面將從多個方面進行分析…

    編程 2025-04-29
  • 使用vscode建立UML圖的實踐和技巧

    本文將重點介紹在使用vscode在軟件開發中如何建立UML圖,並且給出操作交互和技巧的指導。 一、概述 在軟件開發中,UML圖是必不可少的重要工具之一。它為軟件架構和各種設計模式的…

    編程 2025-04-29
  • Java騰訊雲音視頻對接

    本文旨在從多個方面詳細闡述Java騰訊雲音視頻對接,提供完整的代碼示例。 一、騰訊雲音視頻介紹 騰訊雲音視頻服務(Cloud Tencent Real-Time Communica…

    編程 2025-04-29
  • Java Bean加載過程

    Java Bean加載過程涉及到類加載器、反射機制和Java虛擬機的執行過程。在本文中,將從這三個方面詳細闡述Java Bean加載的過程。 一、類加載器 類加載器是Java虛擬機…

    編程 2025-04-29
  • Java Milvus SearchParam withoutFields用法介紹

    本文將詳細介紹Java Milvus SearchParam withoutFields的相關知識和用法。 一、什麼是Java Milvus SearchParam without…

    編程 2025-04-29
  • Python中的while true:全能編程開發必知

    對於全能編程開發工程師而言,掌握Python語言是必不可少的技能之一。而在Python中,while true是一種十分重要的語句結構,本文將從多個方面對Python中的while…

    編程 2025-04-29
  • Java 8中某一周的周一

    Java 8是Java語言中的一個版本,於2014年3月18日發佈。本文將從多個方面對Java 8中某一周的周一進行詳細的闡述。 一、數組處理 Java 8新特性之一是Stream…

    編程 2025-04-29
  • Java判斷字符串是否存在多個

    本文將從以下幾個方面詳細闡述如何使用Java判斷一個字符串中是否存在多個指定字符: 一、字符串遍歷 字符串是Java編程中非常重要的一種數據類型。要判斷字符串中是否存在多個指定字符…

    編程 2025-04-29
  • VSCode為什麼無法運行Java

    解答:VSCode無法運行Java是因為默認情況下,VSCode並沒有集成Java運行環境,需要手動添加Java運行環境或安裝相關插件才能實現Java代碼的編寫、調試和運行。 一、…

    編程 2025-04-29

發表回復

登錄後才能評論