问题
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.
回答1:
Threads are started with Thread.start
, not Thread.run
. run
will just call the run
method sequentially on the main thread.
You're not even creating threads actually:
public static void main(String[] args) {
Main m = new Main();
Thread t1 = new Thread(m.new SomeThread("t1"));
Thread t2 = new Thread(m.new SomeThread("t2"));
Thread t3 = new Thread(m.new SomeThread("t3"));
t1.start();
t2.start();
t3.start();
}
回答2:
Forget it. It won't work. File locks are held on behalf of the entire process, not individual threads.
来源:https://stackoverflow.com/questions/12616975/how-to-start-concurrent-threads-that-acquire-a-file-lock-and-wait-on-each-other