0

我在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()方法只会使访问同一文件的其他线程等到锁被释放。

4

2 回答 2

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();
}
于 2012-09-27T08:23:21.087 回答
1

忘了它。它行不通。文件锁代表整个进程,而不是单个线程。

于 2012-09-27T08:35:30.420 回答