Java signal handling and then return to main progr

2019-09-08 19:44发布

问题:

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

回答1:

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.