AutoCloseable接口

随着互联网的发展,资源的使用也越来越频繁,同时意味着网络资源将面临前所未有的紧张。从jdk1.7开始,Java提供了AutoCloseable接口来保证每次资源使用完毕后自动关闭,以达到缓解资源紧张的问题。
该接口定义如下:

public interface AutoCloseable {
	void close() throws Exception;
}

模拟使用AutoCloseable接口进行自动释放资源:

interface IChatRoom extends AutoCloseable {
	void send();//模拟消息发送
}

class ChatRoom implements IChatRoom{
	private String message;
	ChatRoom(String message){
		this.message = message;
	}

	//模拟链接资源通道的方法
	public boolean isopen() {
		System.out.println("【连接资源通道成功】");
		return true;
	}
	
	//覆写AutoCloseable接口中的方法,模拟资源通道的关闭
	@Override
	public void close() throws Exception {
		System.out.println("【关闭资源通道成功】");
	}

	@Override
	public void send() {
		if(this.isopen()) {
			if(this.message == "") {
				throw new RuntimeException("您输入的内容为空,不能发送");
			}
			System.out.println("消息发送:" + this.message);
		}
	}
	
}

public class Test_AutoClose {
	public static void main(String[] args) {
		//自动关闭处理机制需要在try语句中创建对象,否则不会自动调用close()方法
		try(ChatRoom cr = new ChatRoom("Hello World!")) {
			cr.send();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

发布了15 篇原创文章 · 获赞 5 · 访问量 703

猜你喜欢

转载自blog.csdn.net/weixin_46192593/article/details/104749153