How to stop a thread waiting in a blocking read operation in Java?

后端 未结 7 1919
萌比男神i
萌比男神i 2020-12-03 10:40

I have a thread that executes the following code:

public void run() {
    try {
        int n = 0;
        byte[] buffer = new byte[4096];
        while ((n          


        
7条回答
  •  没有蜡笔的小新
    2020-12-03 11:07

    If you want to give a user some time to enter data - maybe to allow overriding default values or interrupting some automated process -, then wait first and check available input after the pause:

    System.out.println("Enter value+ENTER within 5 Seconds to override default value: ");
    try{
      Thread.sleep(5000);
    } catch {InterruptedException e){}
    
    try{
      int bytes = System.in.available();
      if (bytes > 0) {
        System.out.println("Using user entered data ("+size+" bytes)");
      } else {
        System.out.println("Using default value"); 
      }
    } catch(IOException e) { /*handle*/ }
    

提交回复
热议问题