views:

236

answers:

6

I am trying to learn Java, I was reading 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 like when you ask the user for input it suspends until the response is recieved? I am used to these things happening asynchronously. Is this normal for Java? or can you do both?

Thanks.

+2  A: 

In order to get this to work the way you want (I'm assuming you have other parts of the application you want to keep running, e.g. a GUI) you're going to need to multithread.

The implementation of TextIO would really be the deciding factor, but in the specific code example above, the while loop depends on that input, so it's going to have to pause at that point regardless of any multithreading.

Jeremy Smyth
+2  A: 

For asynchronous I/O, there is java.nio. But yes, synchronous I/O is typical of Java.

shikhar
A: 

Yeah, that is pretty much how it goes. If you wanted to do it asynchronously you could create the gets in a separate thread.

Tom Hubbard
+4  A: 

I'm not familiar with that TextIO library, but when calling InputStream.read(), i.e. when using System.in.read(), it will block until input data is available. This makes it synchronous.

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

Peter
+1  A: 

..or can you do both?

You can do both.

Normally that class should be using some kind of standard input reading which by default blocks, but it is quite possible to have non blocking reading of streams.

If you post the actual code we could offer a more detailed explanation.

OscarRyz
+2  A: 

Your sending/receiving class may have the following form (old way):

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();
    }

}

I fully recomend this book: Java NIO from O'Reilly. It's a full featured book for synchronous and asynchronous IO.

Oso
Thanks, I like orielly books so I think I'll check that out, I also heard effective java was really good.
John Isaacks