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/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
  • Java腾讯云音视频对接

    本文旨在从多个方面详细阐述Java腾讯云音视频对接,提供完整的代码示例。 一、腾讯云音视频介绍 腾讯云音视频服务(Cloud Tencent Real-Time Communica…

    编程 2025-04-29
  • 使用vscode建立UML图的实践和技巧

    本文将重点介绍在使用vscode在软件开发中如何建立UML图,并且给出操作交互和技巧的指导。 一、概述 在软件开发中,UML图是必不可少的重要工具之一。它为软件架构和各种设计模式的…

    编程 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

发表回复

登录后才能评论