0

I have 2 Thread : main and Thread2.

Main-->create Thread2, sleep for 3 second, exit.

Thread2--> readline from System.in and exit.

I want to wake up Thread2 if it is block in a readline(), i don't want to use timeout, and closing the main inputstream by generating an exception in Thread2 don't work .

The code :

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;

public class Main {    
  public static void main(String[] args) throws InterruptedException {
    InputStreamReader sc = new InputStreamReader(System.in);

    Thread2 t = new Thread2(sc);
    Thread tt = new Thread(t);
    tt.start();

    Thread.sleep(3000);
    System.out.println("exit sleep");

    tt.interrupt();
    System.out.println("exit main");
  }
}

class Thread2 implements Runnable {
  InputStreamReader qst;

  public Thread2(InputStreamReader sc) {
    qst = sc;
  }  
  public void run() {
    BufferedReader buff = new BufferedReader(qst);
    try {
      System.out.println("read thread");

      buff.readLine(); //Here is locked!!!!!!!!!!!!!!!!!!
    } catch (InterruptedIOException e) {
      System.out.println("exit thread");
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Execution (println):

-read Thread

(after 3 second)

-exit sleep

-exit main

But Thread2 non stop--> it is block in a readline. Why?

GhostCat
  • 137,827
  • 25
  • 176
  • 248
John
  • 313
  • 4
  • 17

2 Answers2

0

You can set your thread to deamon:

tt.setDaemon(true);

The doc says:

Marks this thread as either a daemon thread or a user thread. The Java Virtual Machine exits when the only threads running are all daemon threads.

In your case, tt will stop running when the main thread ends.

TMichelsen
  • 327
  • 1
  • 7
0

There are two options here:

  1. As others have suggested, you somehow have to force-close your input stream
  2. You can step back, and consider to re-design your whole thing: Java offers you techniques to do non-blocking IO. You can turn here for some first guidance how to do that.

Of course, it really depends on your context which of the two makes more sense. Option 2 of course means a very much different approach; but on the other hand: if you don't want to block on reads, then well: you should not block on reads.

Community
  • 1
  • 1
GhostCat
  • 137,827
  • 25
  • 176
  • 248