AutoCloseable接口
1:AutoCloseable是什么
AutoCloseable主要用于日后进行资源开发的处理上,以实现资源的自动关闭(释放资源),例如:在以后进行文件,网络,数据库开发的过程中由于服务器的资源有限,所以使用之后一定要关闭资源,这样才可以被更多的使用者所使用。
2:说明资源的问题
public class Test {
public static void main(String[] args) {
NetMessage nm = new NetMessage("www.mldn.cn") ; // 定义要发送的处理
nm.send(); // 消息发送
nm.close(); // 关闭连接
}
}
interface IMessage {
public void send() ; // 消息发送
}
class NetMessage implements IMessage { // 实现消息的处理机制
private String msg ;
public NetMessage(String msg) {
this.msg = msg ;
}
public boolean open() { // 获取资源连接
System.out.println("【OPEN】获取消息发送连接资源。");
return true ;
}
@Override
public void send() {
if (this.open()) {
System.out.println("【*** 发送消息 ***】" + this.msg);
}
}
public void close() {
System.out.println("【CLOSE】关闭消息发送通道。");
}
}
//运行结果
//【OPEN】获取消息发送连接资源。
//【*** 发送消息 ***】www.mldn.cn
//【CLOSE】关闭消息发送通道。
3:能否实现自动关闭的功能
这样就不需要在主方法中书写close方法();
public class JavaAPIDemo {
public static void main(String[] args) throws Exception {
try (IMessage nm = new NetMessage("www.mldn.cn")) {
nm.send();
} catch (Exception e) {}
}
}
interface IMessage extends AutoCloseable {
public void send() ; // 消息发送
}
class NetMessage implements IMessage { // 实现消息的处理机制
private String msg ;
public NetMessage(String msg) {
this.msg = msg ;
}
public boolean open() { // 获取资源连接
System.out.println("【OPEN】获取消息发送连接资源。");
return true ;
}
@Override
public void send() {
if (this.open()) {
System.out.println("【*** 发送消息 ***】" + this.msg);
}
}
public void close() throws Exception {
System.out.println("【CLOSE】关闭消息发送通道。");
}
}
在以后的章节中会接触到资源的关闭问题,往往都会见到AutoCloseable接口的使用。