gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 17:29:16 24 4
gpt4 key购买 nike

我正在研究FileLock 类。我想要做的是启动三个同时运行并访问单个文件的线程。当文件被一个线程锁定时,我希望其他两个线程在锁释放时等待轮到它们。然而,当我运行下面的代码时,这些线程甚至不会同时启动——一旦它们的每个 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() 方法只会让访问同一文件的其他线程等待,直到锁被释放。

最佳答案

线程是通过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();
}

关于java - 如何启动获取文件锁并相互等待的并发线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12616975/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com