如何启动获取文件锁并相互等待的并发线程

时间:2012-09-27 08:21:28

标签: java multithreading file-io thread-safety file-locking

我正在学习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()方法只会让其他线程访问同一个文件,直到锁被释放为止。

2 个答案:

答案 0 :(得分:4)

主题以Thread.start开头,而不是Thread.runrun只会在主线程上按顺序调用run方法。

你甚至没有实际创建线程:

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();
}

答案 1 :(得分:1)

算了。它不会起作用。文件锁代表整个进程而不是单个线程。