java多线程读写文件
发布网友
发布时间:2022-04-26 02:00
我来回答
共1个回答
热心网友
时间:2022-06-19 19:58
public static void main(String[] args) {
File data = new File("data.txt");
try {
InputStreamReader read = new InputStreamReader(new FileInputStream(
data), "UTF-8");
final BufferedReader bufferedReader = new BufferedReader(read);
for (int i = 0; i < 5; i++) {
new Thread(new Runnable() {
@Override
public void run() {
String lineTXT = null;
synchronized (bufferedReader) {
try {
while ((lineTXT = bufferedReader.readLine()) != null) {
System.out.println(Thread.currentThread()+":"+lineTXT);
bufferedReader.notify();
bufferedReader.wait();
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
bufferedReader.notifyAll();
}
}
}
}).start();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}