Java信号处理然后返回主程序

时间:2013-03-20 23:48:06

标签: java signals sigint

MI有一个以for循环开始的程序,它旋转10次,一个循环持续1秒。我需要处理一个信号(CTRL + C)并在处理它时,它应该自己进行循环,并且在它停止之后,我应该返回主循环。我已经成功完成了上面的所有操作,但循环不会单独执行。他们并行做。希望你能帮忙......谢谢:)。

BTW,我的代码是:

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");
    }
  } 
}

1 个答案:

答案 0 :(得分:1)

是的,根据文档,SignalHandler在一个单独的线程中执行:

  

...当VM收到信号时,特殊的C信号处理程序会创建一个   新线程(优先级为Thread.MAX_PRIORITY)运行已注册的   Java信号处理程序..

如果要在执行处理程序时停止主循环,可以添加锁定机制,如下所示:

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();
        }
    }
}

可能有更好的锁定策略。