AutoCloseable主要用于资源开发的处理上,以实现资源的自动关闭(释放资源),
下面通过一个资源的发送处理完成。
范例:手工实现资源处理
public class Test {
public static void main(String[] args) {
NetMessage nm=new NetMessage("www.laofuopso.top");
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.laofuopso.top
【CLOSE】关闭消息发送通道
那么是否可以实现自动关闭呢?推出了AutoCloseable访问接口。并且该接口只提供有一个方法:
关闭方法:public void