[英]Reading and writing a file using threads in java
我試圖從一個文件中讀取 5000 個整數,並使用兩個線程將這些整數寫入另一個文件。 這是我的代碼:
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();
}
}
我使用了生產者消費者算法。 它從文件中讀取並將整數寫入數據類中的值,從數據類中讀取並寫入文件。 但它不能正常工作。 它將零寫入文件。 我的代碼有什么問題?
謝謝
如果是我,我會創建一個單獨的對象來跟蹤對文件的讀取和寫入。
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);
}
}
}
並分別從每個線程調用 write 。 這樣你就不會有多個線程同時寫入同一個文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.