加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 作家是一种原子方法吗?

发布时间:2020-12-15 00:03:40 所属栏目:Java 来源:网络整理
导读:我想给文件写一些字符串.所以,我使用了BufferedWriter类.由于许多线程倾向于写入该文件,我想知道write和writeLine方法是否是原子的. 此外,我希望程序将输出写入多个文件,每个文件100行(比如file.txt0,file.txt1,…).例如 public class Main { static Executo
我想给文件写一些字符串.所以,我使用了BufferedWriter类.由于许多线程倾向于写入该文件,我想知道write和writeLine方法是否是原子的.

此外,我希望程序将输出写入多个文件,每个文件100行(比如file.txt0,file.txt1,…).例如

public class Main {
    static ExecutorService exec = Executors.newFixedThreadPool(5);
    BufferedWriter bw;
    public class myWriter implements Runnable {
        String str;
        myWriter (String str) {
            this.str = str;
        }
        public void run() {
            bw.write(str);
            bw.writeLine();
        }
    }
    public static void main(String[] args) {
        bw = new BufferedWriter(new  FileWriter("train.txt"));
        for (String arg: args)
            exec.execute(new myWriter(arg));
        exec.awaitTermination(100000,TimeUnit.MILLISECONDS);
    }
}

有人能帮我吗?如果它们不是原子的,我怎样才能使它们成为原子并避免碰撞?

解决方法

不,那些不是原子的.

如果要将多个磁带写入同一文件,请使用FileLocks.

try {
    // Get a file channel for the file
    File file = new File("filename");
    FileChannel channel = new RandomAccessFile(file,"rw").getChannel();

    // Use the file channel to create a lock on the file.
    // This method blocks until it can retrieve the lock.
    FileLock lock = channel.lock();

    // Try acquiring the lock without blocking. This method returns
    // null or throws an exception if the file is already locked.
    try {
        lock = channel.tryLock();
    } catch (OverlappingFileLockException e) {
        // File is already locked in this thread or virtual machine
    }

    // Release the lock
    lock.release();

    // Close the file
    channel.close();
} catch (Exception e) {
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读