- 论坛徽章:
- 0
|
简单实现了一下,仅供参考:
- public class Test {
- private int flag = 0;
-
- public void A() {
- while (flag == 0) {
- System.out.println("###################");
- }
- }
-
- public void B() {
- flag = 1;
- for (int i = 10; i >= 0; i--) {
- System.out.println(i);
- }
- }
- }
复制代码
- import java.lang.reflect.InvocationTargetException;
- public class CtrlCTest extends Thread {
- private static CtrlCTest ctrlCTest = null;
- public static void registerCtrlCTest() throws IllegalArgumentException,
- InvocationTargetException, NoSuchMethodException,
- SecurityException, IllegalAccessException {
- if (ctrlCTest == null) {
- ctrlCTest = new CtrlCTest();
- Class[] cls = { Thread.class };
- Object[] arg = { ctrlCTest };
- Runtime.getRuntime().getClass().getMethod("addShutdownHook", cls).invoke(
- Runtime.getRuntime(), arg);
- }
- }
- public void run() {
- System.out.println("do run");
- TestMain.shutdown();
- }
- }
复制代码
- public class TestMain {
- private static Test test = null;
- public static void main(String args[]) {
- test = new Test();
- try {
- CtrlCTest.registerCtrlCTest();
- test.A();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- public static void shutdown() {
- if(test!=null) {
- test.B();
- test = null;
- }
- }
- }
复制代码 |
|