简体   繁体   中英

Reading and writing a file using threads in java

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

If it were me I would create a separate object to keep track of the reading and writing to the file.

public class fileHandler{
    File f;
    printWriter p

    public void fileHandler(String filename){
        f = new File(filename);
        p = new printWriter(f);
    }

    public void write(String str){
        synchronized(p){
            p.println(str);
        }
    }
}

and just call write from each thread individually. This way you don't have multiple threads writing to the same file at the same time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM