package com.thinkinjava.concurrency;

import java.util.concurrent.TimeUnit;

class NeedsCleanup {
    private final int id;
    public NeedsCleanup(int id) { this.id = id; }
    public void cleanup() {
        System.out.println("clean up " + id);
    }
}


class Block3 implements Runnable {
    private volatile double d = 1.0;

    public void run() {
        try {
            while(!Thread.currentThread().isInterrupted()) {
                NeedsCleanup n1 = new NeedsCleanup(1);
                try {
//                    TimeUnit.SECONDS.sleep(10);
                    System.out.println(System.currentTimeMillis() + ": start time-consuming ...");
                    for (long i = 0; i < 650000000; i++) {
                        d = d + (Math.PI + Math.E) / d;
                    }
                    System.out.println(System.currentTimeMillis() + ": finish");
                } finally {
                    n1.cleanup();
                }
            }
        } finally {
            System.out.println("exiting via interrupt");
        }
    }
}

public class InterruptingIdioim {
    public static void main(String[] args) throws Exception {
        Thread t = new Thread(new Block3());
        t.start();
        TimeUnit.SECONDS.sleep(1);
        System.out.println(System.currentTimeMillis() + ": interrupting ...");
        t.interrupt();
    }
}
