forked from tianshb/JavaLearning
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUseFileLocks.java
More file actions
38 lines (30 loc) · 996 Bytes
/
Copy pathUseFileLocks.java
File metadata and controls
38 lines (30 loc) · 996 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.crow;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
/**
* Created by CrowHawk on 17/9/4.
*/
public class UseFileLocks {
static private final int start = 10;
static private final int end = 20;
public static void main(String[] args) throws Exception {//使用文件锁的示例
RandomAccessFile raf = new RandomAccessFile("ReadAndShow.txt", "rw");
FileChannel fc = raf.getChannel();
//Get Lock
System.out.println("Trying to get lock.");
FileLock lock = fc.lock(start, end, false);
System.out.println( "got lock!" );
// Pause
System.out.println( "pausing" );
try {
Thread.sleep( 3000 );
} catch( InterruptedException ie ) {
}
// Release lock
System.out.println( "going to release lock" );
lock.release();
System.out.println( "released lock" );
raf.close();
}
}