AutoCloseable主要是用于资源操作时,实现资源的自动关闭。例如在进行数据库访问时,数据库的链接有限,在操作完成后要及时关闭,此时就可以使用AutoCloseable进行自动关闭。
interface IMessage {
void send();
}
class NetMessage implements IMessage {
private String msg;
public NetMessage(String msg) {
this.msg = msg;
}
public void open() {
System.out.println("[ OPEN] ==> 获取连接资源");
}
@Override
public void send() {
System.out.println("[ SEND] ==> " + this.msg);
}
public void close() {
System.out.println("[CLOSE] ==> 关闭资源");
}
}
public class Application {
public static void main(String[] args) {
NetMessage nm = new NetMessage("Hello World");
nm.open();
nm.send();
nm.close();
}
}
interface IMessage {
void send();
}
class NetMessage implements IMessage, AutoCloseable {
private String msg;
public NetMessage(String msg) {
this.msg = msg;
}
public void open() {
System.out.println("[ OPEN] ==> 获取连接资源");
}
@Override
public void send() {
System.out.println("[ SEND] ==> " + this.msg);
}
@Override
public void close() throws Exception {
System.out.println("[CLOSE] ==> 关闭资源");
}
}
public class Application {
public static void main(String[] args) {
try (NetMessage nm = new NetMessage("Hello World")) {
nm.open();
nm.send();
} catch (Exception e) {
e.printStackTrace();
}
}
}