java文件锁定_Java文件锁定

我有几个线程(其中一些是由Process X产生的,另一个由Process Y等等),每个线程都需要写入一个文件MyFile.但是,如果线程T1首先开始写入MyFile,那么当Thread T2开始写入时,需要等待T1释放该文件,以便读取在线程T1中写入的内容.换句话说,每个线程都会有一个finalizeThread方法,像这样:

private void finalizeThread() {

File f = new File("MyFile.dat");

f.createNewFile(); // atomically creates the file, if it doesn't exist

locked_section {

readContentsFromFile(f); // read contents if some other thread already modified the file

modifyContentsFromFile(f); // modify

writeFile(f); // write, so that new threads can see the content modified by this thread

}

}

我的问题是:如何在上述代码中完成locked_section?我正在研究FileLock类,但是它在Javadoc中说:“文件锁代表整个Java虚拟机,它们不适用于通过同一虚拟机中的多个线程控制对文件的访问.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值