Here is a program that attempts to read 2 sentences from a file. For some reason the program attempts to read from a new thread . Before starting a new thread i initialize the BufferedReader object and pass it as a reference to a function that initiates a thread. Now i have 2 references of the BufferedReader object and i try to read the sentences from the main thread and the new thread created.
In the file the 2 sentences on new lines are :
D:\UnderTest\wavtester_1.wav
D:\UnderTest\wavtester_2.wav
But the output is surprising:
FROM THE MAIN THREAD D:\UnderTest\wavtester_1.wav
ON A NEW THREAD D:\UnderTest\wavtester_2.wav
FROM THE MAIN THREAD
If we notice, the new thread does not read the first sentence and the first sentence has been read by the main thread. Also the 3rd output prints white space in front of FROM THE MAIN THREAD when the 2nd statement has been read by the new thread. So, should i interpret that the 2 references are actually one ?
If i am wrong then what actually is happening ?
import java.io.*;
class tester {
public static void main( String args[] ) {
try {
BufferedReader bfr = new BufferedReader( new FileReader( new File( "e:\\AVS Player\\AudioPlaylists\\tester.txt") ) );
// pass a reference of bfr and start a new thread
startThread( bfr );
String y = null;
while( ( y = bfr.readLine() ) != null ) {
System.out.println("FROM THE MAIN THREAD" + " " + y );
}
} catch( Exception exc ) {
System.out.println( exc );
}
}
private static void startThread( final BufferedReader bfr ) {
Runnable r = new Runnable() {
@Override
public void run() {
fnctn( bfr );
}
};
new Thread(r).start();
}
private static void fnctn( BufferedReader bfr ) {
String x = null;
try {
//BufferedReader bfr1 = new BufferedReader( new FileReader( new File( "e:\\AVS Player\\AudioPlaylists\\tester.txt") ) );
while( ( x = bfr.readLine() ) != null ) {
System.out.println("ON A NEW THREAD" + " " + x);
}
} catch( Exception exc ) {
System.out.println( exc );
}
}
}
As against this if in the method fnctn i initialize a new BufferedReader object and read from that reference the output is :
FROM THE MAIN THREAD D:\UnderTest\wavtester_1.wav
FROM THE MAIN THREAD D:\UnderTest\wavtester_2.wav
FROM THE MAIN THREAD
ON A NEW THREAD D:\UnderTest\wavtester_1.wav
ON A NEW THREAD D:\UnderTest\wavtester_2.wav
ON A NEW THREAD
What does this output indicate ?
The two references refer to the same instance of BufferedReader.
Therefore, if one thread reads something the next or the same thread continues to read from the last position.
In your second example you create two different readers which have different internal states (read position).