I am learning java thread and i wrote below code and try to run this code. i am not using any synchronize concept but output is in consistent format. Please help me to figure out the actual reason.
package check;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
public class Hello {
public static void main(String[] args) throws FileNotFoundException, IOException {
Write write = new Write();
String str[] = new String[5];
String str2[] = new String[5];
for (int i = 0 ; i < 5; i ++) {
str[i] = System.getProperty("line.separator") + " hello this is a new line written at " + new Date().toString();
str2[i] = System.getProperty("line.separator") + " this is code after new line " + new Date().toString();
}
new Th(str, write).start();
new Th(str2 , write).start();
}
}
class Th extends Thread {
private String[] message;
private Write write;
Th(String[] message, Write write) {
this.message = message;
this.write = write;
}
public void run() {
try {
write.write(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Write {
public void write(String[] message) throws IOException {
FileWriter fileWriter = null;
BufferedWriter bufferedWriter = null;
try {
fileWriter = new FileWriter("d:/a.txt", true);
bufferedWriter = new BufferedWriter(fileWriter);
for (String msg : message) {
System.out.println(Thread.currentThread().getName());
bufferedWriter.write(msg);
Thread.sleep(500);
}
} catch (Exception e) {
System.out.println(e);
} finally {
bufferedWriter.close();
fileWriter.close();
}
}
}
I know that, write method of Writer class use synchronize block internally like :
public void write(String str, int off, int len) throws IOException {
synchronized (lock) {
char cbuf[];
if (len <= WRITE_BUFFER_SIZE) {
if (writeBuffer == null) {
writeBuffer = new char[WRITE_BUFFER_SIZE];
}
cbuf = writeBuffer;
} else { // Don't permanently allocate very large buffers.
cbuf = new char[len];
}
str.getChars(off, (off + len), cbuf, 0);
write(cbuf, 0, len);
}
}
My program output is :
this is code after new line Thu Mar 16 19:33:07 IST 2017
this is code after new line Thu Mar 16 19:33:07 IST 2017
this is code after new line Thu Mar 16 19:33:07 IST 2017
this is code after new line Thu Mar 16 19:33:07 IST 2017
this is code after new line Thu Mar 16 19:33:07 IST 2017
hello this is a new line written at Thu Mar 16 19:33:07 IST 2017
hello this is a new line written at Thu Mar 16 19:33:07 IST 2017
hello this is a new line written at Thu Mar 16 19:33:07 IST 2017
hello this is a new line written at Thu Mar 16 19:33:07 IST 2017
hello this is a new line written at Thu Mar 16 19:33:07 IST 2017
My question is: why not second thread write data after first thread come out from synchronize block of write method. thanks :)