I'm studying the FileLock
class. What I want to do is start three Threads
that will run at the same time and access a single file. While the file is locked by one thread, I want the other two threads to wait for their turn when the lock is released. However, when I run my code below, the threads don't even start all at the same time--they are started one after the other, as soon as each of their run()
methods is finished. I don't understand.
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();
}
}
}
}
}
}
How can I achieve the scenario I'm trying to get at? And why aren't they starting at the same time? I thought the lock()
method only makes the other threads accessing the same file wait until the lock is released.
Forget it. It won't work. File locks are held on behalf of the entire process, not individual threads.
Threads are started with
Thread.start
, notThread.run
.run
will just call therun
method sequentially on the main thread.You're not even creating threads actually: