java多线程读写文件
用多线程读我能理解。但我看网上有用多线程文件读写的,可是多线程就要加锁,同一时间只能有一个线程工作,这跟单线程有什么区别?而且加锁还要浪费性能,这么做真的会加快写入速度?...
用多线程读我能理解。但我看网上有用多线程文件读写的,可是多线程就要加锁,同一时间只能有一个线程工作,这跟单线程有什么区别?而且加锁还要浪费性能,这么做真的会加快写入速度?
展开
1个回答
展开全部
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();
}
}
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();
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询