zm
2020-05-18 a18bfacbf56b401f6e0fdae8710fbca4df8cff77
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.codingapi.tx.framework.thread;
 
import com.codingapi.tx.Constants;
 
import java.util.concurrent.TimeUnit;
 
/**
 * create by lorne on 2017/8/9
 */
public abstract class HookRunnable implements Runnable {
 
    private volatile boolean hasOver;
 
    @Override
    public void run() {
        Thread thread = new Thread() {
            @Override
            public void run() {
                Constants.hasExit = true;
                while (!hasOver) {
                    try {
                        TimeUnit.MILLISECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        if (!Constants.hasExit) {
            Runtime.getRuntime().addShutdownHook(thread);
        } else {
            // System.out.println("jvm has exit..");
            return;
        }
        try {
            run0();
        } finally {
 
            hasOver = true;
 
            if (!thread.isAlive()) {
                Runtime.getRuntime().removeShutdownHook(thread);
            }
        }
    }
 
    public abstract void run0();
 
}