Java同步外部文件读写

标签 java multithreading

我想创建一个管道,用于在 2 个 JVM 进程(不是同一进程)之间读/写数据。我在 Unix 中使用 FIFO 管道来共享数据。

我做了一个阅读器:

/** Read a named pipe file */
public class PipeReader {

private String path;

public PipeReader (String path) {
    this.path = path;
}

public String readpipe () throws IOException { 
    String res = null;
    RandomAccessFile pipe = null;

    try {
        // Connect to the named pipe
        pipe = new RandomAccessFile (path, "r");

        // Read response from pipe
        while (true) {
           res = pipe.readLine();
           System.out.println("Read message:" + res);   
        }    
    } catch (Exception e) { 
        e.printStackTrace();
    } finally {
        pipe.close();
    }
    return res;
}

以及使用 FileLock 的 Writer:

public class PipeWriter {

private String path;

public PipeWriter (String path) {
    this.path = path;
}

public String writepipe (String mm) throws IOException { 
    String res = null;
    RandomAccessFile pipe = null;
    try {
        // Connect to the named pipe
        pipe = new RandomAccessFile (path, "rw");
        FileChannel channel = pipe.getChannel();
        int i = 0;
        while (i<5) {   
            // Write request to the pipe
            FileLock lock = channel.lock();
            pipe.write(mm.getBytes());
            lock.release();
            System.out.println("PipeWriten" + mm);
            Thread.sleep(3000);
            i++;
        }



        // do something with res
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // Close the pipe
        pipe.close();
    }


    return res;
}

第一次pipe.readLine()阻塞该线程并等待PipeWriter在管道中写入一行并释放锁,当写入器完成读取器读取它时。这是 PipeWriter 完成之前的行为(在 5 次写入之后)。之后,pipe.readLine() 不会阻塞线程并继续循环读取,因此我多次收到“Read message: null”。我该如何解决它?我想我在《读者》中遗漏了一些东西。有没有什么方法可以同步2个进程共享的文件,而不是使用FileLock? (类似于信号量,但用于进程,而不是线程)。

提前致谢。

最佳答案

管道不像文件(这很好,因为你不能等待文件),它是读取器和写入器之间的连接。它更像是一部电话。当对方挂断电话时,你也必须挂断电话。然后您就可以等待下一个电话了。

read变为零时,这意味着连接现已关闭,您应该关闭管道。如果您想等待新的连接,请重新打开管道。

关于Java同步外部文件读写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32581977/

相关文章:

Java JTable 更新行

ios - 使用 RxSwift 阻塞线程

java - 原子操作和多线程

multithreading - 未发出线程之间的 PyQt 信号

c# - 线程池中排队的任务正在退出,不会被释放回池中

java - 将数组从最高到最低排序

java - 在android中将字符串数组的ArrayList从一个 Activity 传递到另一个 Activity

java - ArrayIndexOutOfBoundsException 错误 : 0

java - 在 Jersey 中,我可以将 QueryParams 和 FormParams 组合成一个方法的值吗?

ruby - 我应该如何使用 Concurrent-Ruby 限制线程创建?