java退出主程序,Java信号处理,然后返回主程序

MI have a program that starts with for loop and it spins for 10 times, and one loop lasts one second. I need to handle a signal (CTRL+C) and while handling it, it should do it's own for loop, and after it stops, then I should return to the main loop. I've managed to do almost everything above, but the loops don't execute separately. They do it parallel. Hope you can help... thanks :)

BTW, my code is:

import sun.misc.Signal;

import sun.misc.SignalHandler;

public class MySig {

public static void shhh(int s){ //s -> seconds :)

s = s*1000;

try{

Thread.sleep(s);

}catch(InterruptedException e){

System.out.println("Uh-oh :(");

}

}

public static void main(String[] args){

Signal.handle(new Signal("INT"), new SignalHandler () {

public void handle(Signal sig) {

for(int i=0; i<5; i++){

System.out.println("+");

shhh(1);

}

}

});

for(int i=0; i<10; i++) {

shhh(1);

System.out.println(i+"/10");

}

}

}

解决方案

Right, according to the docs, SignalHandler is executed in a separate thread:

...when the VM receives a signal, the special C signal handler creates a

new thread (at priority Thread.MAX_PRIORITY) to run the registered

Java signal handler..

If you want to stop your main loop while the handler is executing, you can add a locking mechanism, something like this:

private static final ReentrantLock lock = new ReentrantLock(true);

private static AtomicInteger signalCount = new AtomicInteger(0);

public static void shhh(int s) { // s -> seconds :)

s = s * 1000;

try {

System.out.println(Thread.currentThread().getName() + " sleeping for "

+ s + "s...");

Thread.sleep(s);

} catch (InterruptedException e) {

System.out.println("Uh-oh :(");

}

}

public static void main(String[] args) throws Exception {

Signal.handle(new Signal("INT"), new SignalHandler() {

public void handle(Signal sig) {

// increment the signal counter

signalCount.incrementAndGet();

// Acquire lock and do all work

lock.lock();

try {

for (int i = 0; i < 5; i++) {

System.out.println("+");

shhh(1);

}

} finally {

// decrement signal counter and unlock

signalCount.decrementAndGet();

lock.unlock();

}

}

});

int i = 0;

while (i < 10) {

try {

lock.lock();

// go back to wait mode if signals have arrived

if (signalCount.get() > 0)

continue;

System.out.println(i + "/10");

shhh(1);

i++;

} finally {

// release lock after each unit of work to allow handler to jump in

lock.unlock();

}

}

}

There might be a better locking strategy.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值