AutoCloseable接口
主要适用于资源开发的处理上,以实现资源的自动关闭(释放资源),比如数据库开发的过程中,由于服务器资源有限,所以使用之后一定是关闭资源,这样才可以被更多的资源使用
范例:手工实现资源处理
package org.example; /** * @author Hxw * @date 2024/6/12 * @Description */ interface IMessage { void send();//消息发送 } class netMessage implements IMessage {//实现消息的处理机制 private final String msg; public netMessage(String msg) { this.msg = msg; } public boolean open() {//获取资源链接 System.out.println("[获取消息发送连接资源,OPEN]"); return true; } public void close() { System.out.println("[关闭消息发送连接资源,CLOSE]"); } @Override public void send() { System.out.println("[发送消息:" + this.msg + "]"); } } public class AutoCloseable { public static void main(String[] args) { netMessage nm = new netMessage("Hello,world");//定义要发送的处理 if (nm.open()) {//是否打开了链接 nm.send();//消息发送 nm.close();//关闭链接 } } }
既然所有的资源完成处理之后,都必须进行关闭操作,能否实现一种自动关闭功能
要想实现自动关闭处理,除了使用autocloseable之外,还得结合异常处理语句才能正常完成调用
范例:实现自动关闭处理
package org.example; /** * @author Hxw * @date 2024/6/12 * @Description */ interface IMessage extends java.lang.AutoCloseable { void send(); // 消息发送 } class NetMessage implements IMessage { // 实现消息的处理机制 private final String msg; private boolean isOpen = false; // 用于记录是否已经打开资源 public NetMessage(String msg) { this.msg = msg; } public boolean open() { // 获取资源链接 if (!isOpen) { System.out.println("[获取消息发送连接资源,OPEN]"); isOpen = true; return true; } return false; } @Override public void send() { if (isOpen) { System.out.println("[发送消息:" + this.msg + "]"); } else { System.out.println("[未打开资源,无法发送消息]"); } } @Override public void close() throws Exception { if (isOpen) { System.out.println("[关闭消息发送连接资源,CLOSE]"); isOpen = false; } } } public class AutoCloseable { public static void main(String[] args) { try (NetMessage nm = new NetMessage("Hello, world")) { // 使用 try-with-resources 语句自动关闭资源 nm.open(); // 打开资源 nm.send(); // 消息发送 } catch (Exception e) { System.out.println("[消息发送失败]"); e.printStackTrace(); } } }