java碰撞停止函数,在Java中返回/停止在keypress上执行函数

I have a certain function in my program that I want to stop on the press of a key. I have a native keyboard hook set up for that purpose. Right now, I call System.exit(0) when that key is detected. However, I don't want to exit the program, just stop that operation and return to where it was called. An example is given below.

public class Main {

public static void main(String[] args) {

System.out.println("Calling function that can be stopped with CTRL+C");

foo(); // Should return when CTRL+C is pressed

System.out.println("Function has returned");

}

}

I've tried putting the call to foo() in a thread so I could call Thread.interrupt() but I want the function call to be blocking, not non-blocking. Also there are blocking IO calls in foo() so I'd rather not deal with interrupts unless it's necessary, because I'd have to deal with ClosedByInterruptException exceptions and that has caused problems before.

Also the body of foo() is very long and has many function calls inside it, so writing if (stop == true) return; in the function is not an option.

Is there a better way to do this than making a blocking thread? If so, how? If not, how would I make a blocking thread?

解决方案

How about this?

// Create and start the thread

MyThread thread = new MyThread();

thread.start();

while (true) {

// Do work

// Pause the thread

synchronized (thread) {

thread.pleaseWait = true;

}

// Do work

// Resume the thread

synchronized (thread) {

thread.pleaseWait = false;

thread.notify();

}

// Do work

}

class MyThread extends Thread {

boolean pleaseWait = false;

// This method is called when the thread runs

public void run() {

while (true) {

// Do work

// Check if should wait

synchronized (this) {

while (pleaseWait) {

try {

wait();

} catch (Exception e) {

}

}

}

// Do work

}

}

}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值