java 中断程序_java-中断线程以等待用户输入,然后退出应用程序

这样就解决了问题:

class InputInterruptionExample {

private UserInputThread userInputRunnable;

private Thread userInputThread;

private Thread interrupterThread;

InputInterruptionExample() {

this.userInputRunnable = new UserInputThread();

this.userInputThread = new Thread(userInputRunnable);

this.interrupterThread = new Thread(new InterrupterThread());

}

void startThreads() {

this.userInputThread.start();

this.interrupterThread.start();

}

private class UserInputThread implements Runnable {

private InputStreamReader isr;

private BufferedReader br;

UserInputThread() {

InputStreamReader isr = new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(isr);

}

public void run() {

try {

System.out.println("enter your name: ");

try{

String userInput = br.readLine();

} catch(NullPointerException e) {}

} catch (IOException e) {

System.out.println("Oops..somethign went wrong.");

System.exit(1);

}

}

public void closeBufferdReader() {

try {

System.in.close();

} catch (IOException e) {

System.out.println("Oops..somethign went wrong in closeBufferdReader() method");

System.exit(1);

}

}

}

private class InterrupterThread implements Runnable {

public void run() {

try {

sleep(1000);

userInputRunnable.closeBufferdReader();

userInputThread.interrupt();

userInputThread.join();

System.out.println("Successfully interrupted");

} catch (InterruptedException e) {}

}

}

public static void main(String[] args) {

InputInterruptionExample exampleApp = new InputInterruptionExample();

exampleApp.startThreads();

}

}

更新:仅当以这种方式拆分BufferedReader时,此方法才有效:

InputStreamReader isr = new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(isr);

String userInput = br.readLine();

由于某些原因,当将readLine()结构编写为单行时,中断似乎不起作用:

this.userInput = (new BufferedReader(new InputStreamReader(System.in))).readLine();

因此,尽管可以中断拆分后的BufferedReader结构中的线程,但现在无法读取用户的输入.

如果有人能够显示出一种能够获取用户输入并在用户未及时提供任何输入(中断器处于睡眠状态时)中断UserInputThread的方法,请执行此操作.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值