JAVA高级编程开发技巧

发布时间:2023-05-19

一、多线程

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