[轉] How do I trap CTRL-C in my Java app?

[code]
// The Shutdown class is a sample class to illustrate the
// use of the addShutdownHook method
class Shutdown {
private Thread thread = null;

public Shutdown() {
thread = new Thread("Sample thread") {
public void run() {
while (true) {
System.out.println("[Sample thread] Sample thread speaking...");
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException ie) {
break;
}
}
System.out.println("[Sample thread] Stopped");
}
};
thread.start();
}

public void stopThread() {
thread.interrupt();
}
}


// The ShutdownThread is the thread we pass to the
// addShutdownHook method
class ShutdownThread extends Thread {
private Shutdown shutdown = null;

public ShutdownThread(Shutdown shutdown) {
super();
this.shutdown = shutdown;
}

public void run() {
System.out.println("[Shutdown thread] Shutting down");
shutdown.stopThread();
System.out.println("[Shutdown thread] Shutdown complete");
}
}


// And finally a Main class which tests the two classes
// We let the sample thread run for 10 seconds and then
// force a Shutdown with System.exit(0). You may stop the
// program early by pressing CTRL-C.
public class Main {
public static void main(String [] args) {
Shutdown shutdown = new Shutdown();
try {
Runtime.getRuntime().addShutdownHook(new ShutdownThread(shutdown));
System.out.println("[Main thread] Shutdown hook added");
} catch (Throwable t) {
// we get here when the program is run with java
// version 1.2.2 or older
System.out.println("[Main thread] Could not add Shutdown hook");
}

try {
Thread.currentThread().sleep(10000);
} catch (InterruptedException ie) {
}
System.exit(0);
}
}
[/code]

ref: http://www.esus.com/docs/GetQuestionPage.jsp?uid=392
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值