我在FileLock
上课。我想要做的是启动三个Threads
将同时运行并访问一个文件。当文件被一个线程锁定时,我希望其他两个线程在释放锁时等待轮到它们。但是,当我在下面运行我的代码时,线程甚至不会同时启动——它们会一个接一个地启动,只要它们的每个run()
方法完成。我不明白。
public class Main {
public static void main(String[] args) {
Main m = new Main();
SomeThread t1 = m.new SomeThread("t1");
SomeThread t2 = m.new SomeThread("t2");
SomeThread t3 = m.new SomeThread("t3");
t1.run();
t3.run();
t2.run();
}
class SomeThread implements Runnable {
String name;
public SomeThread(String s) {
name = s;
}
@Override
public void run() {
System.out.println(name + " started!");
OtherClass.access(name);
}
}
static class OtherClass {
static File file = new File("testfile.txt");
public static void access(String name) {
FileChannel channel = null;
FileLock lock = null;
try {
channel = new RandomAccessFile(file, "rw").getChannel();
lock = channel.lock();
System.out.println("locked by " + name);
Thread.sleep(3000);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (lock != null) {
try {
lock.release();
System.out.println("released by " + name);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (channel != null) {
try {
channel.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
我怎样才能实现我想要达到的场景?为什么他们不同时开始?我认为该lock()
方法只会使访问同一文件的其他线程等到锁被释放。