AutoCloseable接口实现资源自动关闭

package com.lxxu.autocloseable;
public class MessageDemo {
	public static void main(String[] args) throws Exception {
		try(NetMessage nm = new NetMessage("sssss")) {
			if(nm.open()){
				nm.send();
			}
		} catch (Exception e) {
			
		}
		
	}
}
interface IMessage extends AutoCloseable{//一定要结合异常处理 JDK1.7引入
	public void send();//消息发送
}
class NetMessage implements IMessage{
	private String msg ;
	public NetMessage(String msg) {
		this.msg = msg;
	}
	public  boolean open(){
		System.out.println("获取消息发送连接资源");
		return true;
	}
	public void close() throws Exception{
		System.out.println("关闭消息发送通道");
	}
	@Override
	public void send() {
		System.out.println("发送消息"+this.msg);
	}
}

猜你喜欢

转载自blog.csdn.net/qq_42740745/article/details/84964645