AutoCloseable主要是用于日后进行资源开发的处理上,以实现资源的自动关闭(释放资源),例如:在以后进行文件、网络、数据库开发的过程之中由于服务器的资源有限,所以使用之后一定要关闭资源,这样才可以被更多的使用者所使用
下面为了更好的说明资源的问题,将通过一个消息的发送处理来完成。
//常规方法实现资源关闭
public class _28 {
public static void main(String[] args) {
IMessage nm = new IMessage("tangxz.jiagoushi");//定义要发送的数据
if (nm.open()){//是否打开了连接
nm.send();//消息发送
}
}
}
class IMessage {
private String msg;
public IMessage(String msg) {
this.msg = msg;
}
public boolean open() {//获取资源链接
System.out.println("【OPEN】获取消息发送连接资源。");
return true;
}
public void close() {
System.out.println("【CLOSE】关闭消息发送通道");
}
public void send() {
if (this.open()) {
System.out.println("【*** 发送消息 ***】" + this.msg);
}
}
}
既然所有的资源完成处理之后都必须进行关闭操作,那么能否实现一种自动关闭的功能呢?,JDK1.7的时候提供的AutoCloseable接口,该接口只提供一个方法close()。
-
关闭方法:public void close() throws Exception;
要想实现自动关闭,除了要使用AutoCloseable之外,还需要结合有异常处理语句才可以完成。
//AutoCloseable实现资源关闭
public class _28_2 {
public static void main(String[] args) {
try(IMessage2 nm = new IMessage2("www.mldn.cn")){
nm.send();
}catch (Exception e){}
}
}
class IMessage2 implements AutoCloseable {
private String msg;
public IMessage2(String msg) {
this.msg = msg;
}
public boolean open() {//获取资源链接
System.out.println("【OPEN】获取消息发送连接资源。");
return true;
}
@Override
public void close() {
System.out.println("【CLOSE】关闭消息发送通道");
}
public void send() {
if (this.open()) {
System.out.println("【*** 发送消息 ***】" + this.msg);
}
}
}