I am trying to read 5000 integers from a file and write these integers to another file using two threads. Here is my code:
public class data {
int value;
}
import java.util.*;
import java.io.*;
public class oku implements Runnable {
data d;
public oku(data d){
this.d=d;
}
public synchronized void run(){
File f= new File("/home/ayyuce/Desktop/ali.dat");
try {
Scanner sc= new Scanner(f);
while(sc.hasNextInt()) {
//synchronized(d) {
d.value=sc.nextInt();
}
//}
sc.close();
} catch(Exception ex){ }
}
}
import java.util.*;
import java.io.*;
public class yaz implements Runnable {
data d;
public yaz(data d) {
this.d=d;
}
public synchronized void run() {
File f= new File("/home/ayyuce/Desktop/veri.dat");
try {
PrintWriter p = new PrintWriter(f);
for(int i=0; i<5000;i++){
//synchronized(d){
p.println(d.value);
//System.out.println(d.value);
}
//}
p.close();
} catch(Exception ex){ }
}
}
public class main_class {
public static void main(String[] args) {
data d= new data();
//d.value=100;
oku o= new oku(d);
yaz y= new yaz(d);
Thread t1= new Thread(o);
Thread t2= new Thread(y);
t1.start();
t2.start();
}
}
I used producer consumer algorithm. It reads from file and writes the integer to the value in the data class and reads from data class, writes to the file. But it does not work correctly. It writes zeros to the file. What is the problem with my code?
Thank you
synchronized void runmakes no sense.BlockingQueue<Integer>to help solve this consumer/producer scenario. However, you were close using a more primitive approach: You had (before commenting them out) wrappedsynchronized(d)around the code in both the consumer and producer, but you did not include the relevantwait()andnotify()methods to co-ordinate a single read, followed by a single write. This primitive approach forces you to lock every single read/write, whereas a blocking queue requires no further synchronization.