自定义错误
public class Main {public static void main(String[] args) {int i = 6;for (int j = 0; j < 10; j++) {try {--i;if (i == 0) {throw new MyError("此时除数为0,但是继续执行for循环!");}System.out.println(6.0 / i);} catch (MyError e) {System.out.println("发现错误:" + e.getMessage());}}}
}
class MyError extends Exception {MyError(String errmessage) {super(errmessage);}
}
策略模式(以读取文件为例,不要用这些方法读取文件!可能会内存泄漏)
import java.io.*;public class Main {public static void main(String[] args) {String filePath = ".\\example.txt";// 按行读取策略Context context = new Context(new LineByLineReadStrategy());context.readFile(filePath);// 按字节读取策略,用于如图片、视频、音频文件context.setStrategy(new ByteByByteReadStrategy());context.readFile(filePath);}
}interface Strategy {void read(String filePath) throws IOException;
}class LineByLineReadStrategy implements Strategy {@Overridepublic void read(String filePath) throws IOException {try (BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath))) {String line;while ((line = bufferedReader.readLine()) != null) {System.out.println(line);}}}
}class ByteByByteReadStrategy implements Strategy {@Overridepublic void read(String filePath) throws IOException {try (FileInputStream fileInputStream = new FileInputStream(filePath)) {int n;while ((n = fileInputStream.read()) != -1) {// 字节打印System.out.print(n+"\n");}}}
}class Context {private Strategy strategy;Context(Strategy strategy) {this.strategy = strategy;}void setStrategy(Strategy strategy) {this.strategy = strategy;}public void readFile(String filePath) {try {strategy.read(filePath);} catch (IOException e) {e.printStackTrace();}}
}
读取文件(安全)
import java.io.*;public class Main {public static void main(String[] args) {String filePath = ".\\example.txt"; int bufferSize = 1024; // 调大可以加快读取速度 try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath))) {byte[] buffer = new byte[bufferSize];int bytesRead;while ((bytesRead = bis.read(buffer)) != -1) {// 由于data是动态创建,当一次while循环结束,gc就会回收data引用的bytesRead// 从而避免了内存泄露String data = new String(buffer, 0, bytesRead, "UTF-8");System.out.print(data);}} catch (IOException e) {e.printStackTrace();}}
}
泛型方法(普通类)
public class Main {public static void main(String[] args) {// Integer类型性能底下,非必须不要用,就用int// 但集合中传入的参数必须是引用类型,不能使用int,比如:// Map<Integer,String> map = new HashMap<>();// List<Integer> list = new ArrayList<Integer>();Integer[] intArray = {1, 2, 3, 4, 5};String[] strArray = {"apple", "banana", "orange"};// 调用泛型方法打印数组,由于是static方法,所以无需实例化。Utils.printArray(intArray);Utils.printArray(strArray);}
}class Utils {// 泛型方法,其中第一个<T>是泛型方法的固定格式public static <T> void printArray(T[] array) {for (T element : array) {System.out.print(element);}}
}
泛型方法(带有泛型类)
class Box<T> {private T content;public Box(T content) {this.content = content;}// 泛型方法public <U> void doSomething(Class<U> type) {}public T getContent() {return content;}
}
自定义日期格式
public class Main {public static void main(String[] args) {// 获取当前日期ZonedDateTime zdt = ZonedDateTime.now();// 中国地区DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy'年'MMM'月'dd'日' EE a hh:mm", Locale.CHINA);// 2024年10月月21日 周一 下午 04:58System.out.println(timeFormatter.format(zdt));}
}
多线程
基本
public class Main {public static void main(String[] args) throws InterruptedException {MyThread t = new MyThread();System.out.println("start");// 置守护线程:不关心此线程是否运行完毕,只要其他非守护线程结束则此主线程会立即退出// 所以不能让置setDaemon的线程持有如:打开文件等...t.setDaemon(true);// 设置线程优先级,默认是5,范围是:0~10 10为最高优先级t.setPriority(5);// 启动t线程,MyThread必须重写run方法,在那里实现业务逻辑t.start();// 设置超时,让主线程等待t实例运行一段时间// 模拟主线程耗时操作Thread.sleep(100);// 标志位置为false,使用他配合while结束t线程t.running = false;// join强制main线程必须等待t结束后在继续执行余下逻辑t.join();System.out.println("Main end...");}
}class MyThread extends Thread {// 线程间共享变量需要使用volatile关键字标记volatile boolean running = true;@Overridepublic void run() {// 这里写需要执行的业务逻辑int n = 0;while (running) {n++;System.out.println(n + " hello!");}System.out.println("This thread end!");}
}