gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 14:44:51 26 4
gpt4 key购买 nike

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

顺便说一句,我的代码是:

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

最佳答案

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

...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..

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

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

可能有更好的锁定策略。

关于Java信号处理然后返回主程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15536952/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com