• No replies
9 Posts

Pinned topic Single-threaded reading from multiple sources

‏2010-08-22T15:22:23Z |
> MariusGav wrote:
> Consider the following lines of code:

//May not compile > BufferedReader[] brs= 

new BufferedReader[16]; > 


int i=0;i<brs.length;i++) > brs=

new BufferedReader(

new InputStreamReader(

new Socket(
"",80).getInputStream())); >

> How can I, for example, write on the screen everything received by the BufferedReaders, only using one thread?
> I thought of something along the lines of



{ > 


int i=0;i<brs.length;i++) > 

if(brs.ready()) > System.out.println(brs.readLine()); > Thread.sleep(42);
//42 was randomly chosen > 
} >

> But it seems inefficient. Is there a more efficient solution?

That's not going to do what you think it's going to do. Assuming that brs[i].ready() returns false (brs.ready() will fail, there is no method of Array called "ready"), you'll never make it back to that instance of BufferedReader (you're only looping once). Even it if did return "true", the best you can do is go one at a time, in order, through your list, since readLine() is a blocking call. If you want asynchronous results, then you have to use threads. No other way around it. (Note, however, if you lose the call to brs[i].ready(), you'll be able to synchronously go through each reader in your array (assuming there are no exceptions).)