Does Java work asynchronously?

I am trying to learn Java, I read a tutorial that said something like this:

while (N <= 0) {
           TextIO.put("The starting point must be positive. Please try again: ");
           N = TextIO.getlnInt();
        }

It seems that when you ask the user for input, it pauses until a response is received? I'm used to what happens asynchronously. Is this normal for Java? or can you do both?

Thanks.

+3
source share
6 answers

I am not familiar with this library TextIO, but when I call InputStream.read () , that is, when I use it System.in.read(), it will block until the input data is available. This makes it synchronous.

You can avoid this (i.e. make it asynchronous) by using another thread to capture input.

+5

- java.nio. , - Java.

+3

/ ( ):

class Sender {

    Integer N = null;
    boolean running;

    public void request(byte [] re) {
        new Thread() {
             public void run() {
                 if(!running)
                     running = true;
                 else
                     synchronized(Sender.this) {try {Sender.this.wait(); }catch(Exception e){}}
                 TextIO.put("The starting point must be positive. Please try again: ");
                 N = TextIO.getlnInt();
                 running = false;
                 synchronized(Sender.this) {try {Sender.this.notify(); }catch(Exception e){}}
             }
        }.start();
    }

    public boolean hasResponse() {
        return N != null;
    }

    public int getResponse() {
        return N.intValue();
    }

}

: Java NIO O'Reilly. -.

+3

, ( , , , , ), .

TextIO , while , - .

+2

.. ?

.

Usually this class should use some standard input reading, which by default blocks, but it is quite possible to have non-blocking reading of streams.

If you publish the actual code, we can offer a more detailed explanation.

+1
source

Yes, this is pretty much how it happens. If you want to do this asynchronously, you can create recipients in a separate thread.

0
source

Source: https://habr.com/ru/post/1711211/


All Articles