【发布时间】:2020-11-25 20:53:23
【问题描述】:
创建k个线程同时将字符写入同一个文件:
- 第一个线程在文件的第一行准确地写入一个数字 0 20 次;
- 第二个线程在文件的第二行写入一个数字 1 正好 20 次;
...
- 第十个线程在文件的第 10 行写入一个数字 9 正好 20 次;
实施要求。
-
每个数字的写入需要设置1毫秒的暂停。
-
使用 RandomAccessFile 将数据写入文件。
-
您只能使用 RandomAccessFile 类的一个对象!
我是这样写的:
import java.io.IOException;
import java.io.RandomAccessFile;
public class Part5 {
// creates string before writing to the file
public static String createString(int integer){
StringBuilder result = new StringBuilder("");
for(int i = 0; i < 20; i++){
result.append(integer);
}
result.append("\n");
return result.toString();
}
// writes string into the file
public static void writeString(String st) {
try(RandomAccessFile file = new RandomAccessFile("part5.txt", "rw")){
st+="\n";
file.write(st.getBytes());
}catch(IOException ex){
ex.getMessage();
}
}
// starts writing threads
public static void startThread(int number){
Thread thread = new Thread(){
@Override
public void run() {
synchronized (this){
writeString(createString(number));
}
}
};
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(final String[] args) {
for(int i = 0; i < 9; i++){
startThread(i);
}
}
}
我的实现只重写文件的第一行,但应该这样写:
00000000000000000000
11111111111111111111
22222222222222222222
33333333333333333333
44444444444444444444
55555555555555555555
66666666666666666666
77777777777777777777
88888888888888888888
99999999999999999999
如何修复代码的“并发部分”以使其正常工作? 提前谢谢!
【问题讨论】:
-
这些要求似乎直接矛盾。如果您必须“使用 RandomAccessFile 将数据写入文件”并且还必须“使用不超过一个 RandomAccessFile 类的对象”,那么线程如何“同时将字符写入同一个文件”?只有一个类的实例,你只有一个文件指针。那么两个线程如何用一个文件指针同时写入呢?
标签: java multithreading concurrency java-io