java学习笔记-第三课

1. 异常处理
1.1 异常的概念
  • 异常:程序运行过程中出现的错误或意外情况,影响程序的正常执行。
  • 异常分类
    • 检查型异常(Checked Exception):必须在编译时处理的异常,如 IOException
    • 非检查型异常(Unchecked Exception):在运行时抛出的异常,如 ArithmeticExceptionNullPointerException
    • 错误(Error):一般不由程序处理的严重问题,如 OutOfMemoryError
1.2 异常处理语法
  • try-catch 语句

    try {
        // 可能抛出异常的代码
    } catch (ExceptionType e) {
        // 处理异常的代码
    }
    
  • 示例

    public class Main {
        public static void main(String[] args) {
            try {
                int result = 10 / 0;
            } catch (ArithmeticException e) {
                System.out.println("Cannot divide by zero");
            }
        }
    }
    
  • finally 语句

    try {
        // 可能抛出异常的代码
    } catch (ExceptionType e) {
        // 处理异常的代码
    } finally {
        // 始终执行的代码
    }
    
  • 示例

     
    public class Main {
        public static void main(String[] args) {
            try {
                int result = 10 / 0;
            } catch (ArithmeticException e) {
                System.out.println("Cannot divide by zero");
            } finally {
                System.out.println("This block is always executed");
            }
        }
    }
    

1.3 自定义异常
  • 定义自定义异常类

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

  • 抛出和捕获自定义异常

    public class Main {
        public static void main(String[] args) {
            try {
                validateAge(15);
            } catch (CustomException e) {
                System.out.println(e.getMessage());
            }
        }
    
        public static void validateAge(int age) throws CustomException {
            if (age < 18) {
                throw new CustomException("Age must be 18 or above");
            }
        }
    }
    

2. 多线程编程
2.1 线程的概念
  • 线程:程序执行的最小单位,Java 中的多线程可以提高程序的并发性和性能。
2.2 创建线程
  • 继承 Thread 类

    public class MyThread extends Thread {
        public void run() {
            System.out.println("Thread is running");
        }
    }
    
    public class Main {
        public static void main(String[] args) {
            MyThread thread = new MyThread();
            thread.start();
        }
    }
    

  • 实现 Runnable 接口

    public class MyRunnable implements Runnable {
        public void run() {
            System.out.println("Thread is running");
        }
    }
    
    public class Main {
        public static void main(String[] args) {
            Thread thread = new Thread(new MyRunnable());
            thread.start();
        }
    }
    

2.3 线程同步
  • 同步方法

    public synchronized void synchronizedMethod() {
        // 线程安全的方法体
    }
    

  • 同步块

    public void method() {
        synchronized(this) {
            // 线程安全的代码块
        }
    }
    

  • 示例

    public class Counter {
        private int count = 0;
    
        public synchronized void increment() {
            count++;
        }
    
        public int getCount() {
            return count;
        }
    }
    
    public class Main {
        public static void main(String[] args) throws InterruptedException {
            Counter counter = new Counter();
    
            Thread t1 = new Thread(() -> {
                for (int i = 0; i < 1000; i++) {
                    counter.increment();
                }
            });
    
            Thread t2 = new Thread(() -> {
                for (int i = 0; i < 1000; i++) {
                    counter.increment();
                }
            });
    
            t1.start();
            t2.start();
    
            t1.join();
            t2.join();
    
            System.out.println("Count: " + counter.getCount());
        }
    }
    

3. 集合框架
3.1 集合的概念
  • 集合:用于存储和操作一组数据的对象。
  • 集合框架:Java 提供的一套接口和类,用于处理集合,如 ListSetMap 等。
3.2 List 接口
  • ArrayList:动态数组,允许重复元素,有序。

    import java.util.ArrayList;
    
    public class Main {
        public static void main(String[] args) {
            ArrayList<String> list = new ArrayList<>();
            list.add("Apple");
            list.add("Banana");
            System.out.println(list.get(0)); // 输出:Apple
        }
    }
    
  • LinkedList:链表,插入和删除效率高。

    import java.util.LinkedList;
    
    public class Main {
        public static void main(String[] args) {
            LinkedList<String> list = new LinkedList<>();
            list.add("Apple");
            list.add("Banana");
            System.out.println(list.get(0)); // 输出:Apple
        }
    }
    
3.3 Set 接口
  • HashSet:不允许重复元素,无序。

    import java.util.HashSet;
    
    public class Main {
        public static void main(String[] args) {
            HashSet<String> set = new HashSet<>();
            set.add("Apple");
            set.add("Banana");
            set.add("Apple"); // 重复元素不会被添加
            System.out.println(set.size()); // 输出:2
        }
    }
    
  • TreeSet:有序集合,基于红黑树实现。

    import java.util.TreeSet;
    
    public class Main {
        public static void main(String[] args) {
            TreeSet<String> set = new TreeSet<>();
            set.add("Banana");
            set.add("Apple");
            set.add("Cherry");
            System.out.println(set); // 输出:[Apple, Banana, Cherry]
        }
    }
    
3.4 Map 接口
  • HashMap:键值对存储,允许 null 键和 null 值,无序。

    import java.util.HashMap;
    
    public class Main {
        public static void main(String[] args) {
            HashMap<String, Integer> map = new HashMap<>();
            map.put("Apple", 1);
            map.put("Banana", 2);
            System.out.println(map.get("Apple")); // 输出:1
        }
    }
    
  • TreeMap:有序键值对存储,基于红黑树实现。

    import java.util.TreeMap;
    
    public class Main {
        public static void main(String[] args) {
            TreeMap<String, Integer> map = new TreeMap<>();
            map.put("Banana", 2);
            map.put("Apple", 1);
            System.out.println(map); // 输出:{Apple=1, Banana=2}
        }
    }
    

小结

  • 本课学习了 Java 的异常处理,包括 try-catch 语句、自定义异常等。
  • 探讨了多线程编程的基本概念和线程同步的实现。
  • 学习了集合框架中的 List、Set 和 Map 接口及其常用实现类。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值