Mar*_*eli 5 java multithreading
我有20个线程用println()函数写入一个名为results.txt的文件.我怎样才能同步它们?
我注意到每次运行程序时,我在results.txt中都有不同数量的文本行.
谢谢.
小智 23
通过包含要写入文件的synchronized方法的类访问该文件.一次只能有一个线程执行该方法.
我认为Singleton模式适合您的问题:
package com.test.singleton;
public class Singleton {
private static final Singleton inst= new Singleton();
private Singleton() {
super();
}
public synchronized void writeToFile(String str) {
// Do whatever
}
public Singleton getInstance() {
return inst;
}
}
Run Code Online (Sandbox Code Playgroud)
每次需要写入文件时,您只需要拨打:
Singleton.getInstance().writeToFile("Hello!!");
Run Code Online (Sandbox Code Playgroud)
重复的问题......重复的答案.正如我在这里所说:
如果您可以将文件保存为FileOutputStream,则可以将其锁定为:
FileOutputStream file = ...
....
// Thread safe version.
void write(byte[] bytes) {
try {
boolean written = false;
do {
try {
// Lock it!
FileLock lock = file.getChannel().lock();
try {
// Write the bytes.
file.write(bytes);
written = true;
} finally {
// Release the lock.
lock.release();
}
} catch ( OverlappingFileLockException ofle ) {
try {
// Wait a bit
Thread.sleep(0);
} catch (InterruptedException ex) {
throw new InterruptedIOException ("Interrupted waiting for a file lock.");
}
}
} while (!written);
} catch (IOException ex) {
log.warn("Failed to lock " + fileName, ex);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
40375 次 |
| 最近记录: |