我试图让两个线程操作同一个文件。问题是它只创建文件(Thread1 责任),但不填充文件(这是 Thread2 责任)。此外,它会挂起,而不会使用退出代码()完成该过程。
这是输出:
File created: example.txt
Thread 1: File creation finished
Run Code Online (Sandbox Code Playgroud)
这是完整的代码:
import java.io.*;
public class ThreadWithFiles {
private static final String FILE_PATH = "/Users/myUser/Desktop/example.txt";
public static void main(String[] args) {
Object lock = new Object();
Thread thread1 = new Thread(() -> {
synchronized (lock) {
createFile();
System.out.println("Thread 1: File creation finished");
lock.notify();
}
});
Thread thread2 = new Thread(() -> {
synchronized (lock) {
try {
lock.wait();
populateFile();
lock.notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
} …Run Code Online (Sandbox Code Playgroud)