Issues with multithreading and file writing
843789Mar 28 2010 — edited Mar 28 2010Hi,
I am trying to understand how a synchronised block. I chose to write to a file using three threads. the program seems to be writing junk characters to file instead of the numbers I am writing, can someone take a look at the below code and help?
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
class writer implements Runnable {
FileWriter first ;
int i;
int j;
BufferedWriter out;
writer(BufferedWriter out, int i, int j)
{
System.out.println("constructor invoked");
this.first=first;
this.i=i;
this.j=j;
this.out=out;
}
public void run() {
// TODO Auto-generated method stub
synchronized (this) {
for (int k=i;k<j;k++)
{
try {
System.out.println("writing the file to "+k);
out.write(k);
//first.write("\n");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public class ThreadTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
File writeFile = new File("test.txt");
FileWriter testFile = new FileWriter(writeFile,true);
BufferedWriter out = new BufferedWriter(testFile);
Runnable R1= new writer(out,100,200);
Runnable R2=new writer(out,200,300);
Runnable R3=new writer(out,300,400);
Thread t1 = new Thread(R1);
Thread t2 = new Thread(R2);
Thread t3 = new Thread(R3);
t1.start();
t2.start();
t3.start();
t1.run();
t2.run();t3.run();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}