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