集册 Java实例教程 AutoCloseable资源类

AutoCloseable资源类

欢马劈雪     最近更新时间:2020-01-02 10:19:05

558
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
AutoCloseable资源类

public class Main {

  public static void main(String[] args) {

    // Its close() method will be called automatically *//**from NowJava.com - 时代Java**/

    try (MyResource mr = new MyResource(2, false)) {

      mr.use();

      mr.use();

    }

    try (MyResource mr = new MyResource(2, true)) {

      mr.use();

      mr.use();

    }

  }

}



class MyResource implements AutoCloseable {

    private int score;

    private boolean errorOut;
/** 来 自 nowjava.com**/

    public MyResource(int level, boolean exceptionOnClose) {

        this.score = level;

        this.errorOut = exceptionOnClose;

        System.out.println("Creating MyResource. Level = " + level);

    }


    public void use() {

        if (score <= 0) {

            throw new RuntimeException("Low in level.");

        }

        System.out.println("Using MyResource level " + this.score);

        score--;

    }


    @Override

    public 
展开阅读全文