简体   繁体   English

文件线程同步

[英]file thread synchronization

How to perform read and write operation by using thread synchronization. 如何通过使用线程同步执行读取和写入操作。

Condition: If one file exists where writers may write information to, only one writer may write at a time. 条件:如果存在一个文件,写入者可以在其中写入信息,则一次只能写入一个写入者。 Confusion may arise if a reader is trying read at the same as a writer is writing. 如果读者尝试的阅读方式与作者撰写的方式相同,则可能会造成混乱。 Since readers only look at the data, but do not modify the data, we can allow more than one reader to read at the same time. 由于读者仅查看数据,而不修改数据,因此我们可以允许多个读者同时阅读。

//reader thread
    class Read extends Thread {
        static File Reader fr1 = null;
        static Buffered Reader br1 = null;

        static synchronized void reader() throws IO Exception {

            String path ="C:/Users/teja/Documents/file1.txt";

            fr1 = new File Reader(path);
            br1 = new Buffered Reader(fr);
            int i;
            while ((i = br. read()) != -1)
                System .out. print((char) i);
            System .out. print ln();
        }

        public void run() {
            try {
                reader();
            } catch (IO Exception e) {
                e. print Stack Trace();
            }
        }
    }
    //writer code
    class Writer extends Thread {
        static Buffered Writer bw1 = null;
        static File Writer fw1 = null;

        static synchronized void writer() throws IO Exception {
            Scanner scanner = new Scanner(System.in);
            System .out .print ln("enter data to be added:");
            String data = scanner. nextLine();

            String path = "C:/Users/vt/Documents/file1.txt";
            fw1 = new File Writer(path, true);

            bw1 = new Buffered Writer(fw1);
            bw1.newLine();
            bw1.write(data);
            bw1.flush();

            scanner. close();
            System. out . println("data added");
        }

        public void run() {
            try {
                writer();
            } catch (IO Exception e) {
                e. print Stack Trace();
            }
        }
    }
    //main method
    public class File Read Write {

        public static void main(String[] args) {
           Read rd1 =new Read();
           Read rd2=new Read();
           Writer wt1=new Writer();

           rd1.run();
           rd2.run();
           wt1.run();
           rd1. run();
            }           
    }

I am new to files and threading in java. 我是Java文件和线程的新手。 I know this is not correct approach. 我知道这不是正确的方法。 Guide me. 引导我。

If one file exists where writers may write information to, only one writer may write at a time. 如果存在一个写入者可以向其中写入信息的文件,则一次只能写入一个写入者。 Confusion may arise if a reader is trying read at the same as a writer is writing. 如果读者尝试的阅读方式与作者撰写的方式相同,则可能会造成混乱。 Since readers only look at the data, but do not modify the data, we can allow more than one reader to read at the same time. 由于读者仅查看数据,而不修改数据,因此我们可以允许多个读者同时阅读。

There are two approaches to this. 有两种方法。

(1) Either lock the resource and have the readers wait until the writer has completed the writing operation (or likewise, have a writer waits until all readers are done). (1)要么锁定资源,要么让读者等待,直到作家完成写操作为止(或者,同样,让作家等待,直到所有读者都完成了)。 This approach guarantees consistency, but can be slow if a lot of writers/readers are working on the resource at the same time (see Lock in java.util.concurrent.locks package). 这种方法保证了一致性,但是如果许多作家/读者同时在资源上工作,则可能会很慢(请参见java.util.concurrent.locks包中的Lock)。

(2) Keep an in-memory-version of the contents of the file that is served to readers only. (2)保留仅提供给读者的文件内容的内存版本。 When a change is made, this in-memory version is updated. 进行更改后,此内存版本将更新。 Here, you'll have more speed, but you lose consistency and you'll need more memory. 在这里,您将获得更快的速度,但是会失去一致性,并且需要更多的内存。

The condition you want to avoid is generally referred as race condition and what you want to avoid it is a synchronization method between threads. 您要避免的条件通常称为race condition而要避免的race condition是线程之间的同步方法。 There are more choices available but the most suitable for your case are mutex and read-write lock . 有更多选择,但最适合您的情况是mutexread-write lock

A mutex basically just lock the resource before any operation on the shared resource is performed, independently from the type of operation and free it after the operation is terminated. mutex基本上只是在对共享资源执行任何操作之前锁定资源,而不受操作类型的影响,并在操作终止后释放资源。 So a read will block the resource and any other operation, read or write will be blocked. 因此,一个read会阻塞资源和任何其他操作, readwrite将被阻止。 A write will block the resource too so again no other read or write operation can be performed before the action is terminated and mutex unlocked. write也会阻塞资源,因此在操作终止和mutex解锁之前,无法再执行其他readwrite操作。 So basically a mutex has 2 states: locked and unlocked. 因此, mutex基本上具有两种状态:锁定和解锁。

read-write lock gives you more freedom based on the fact that read only operations do not result in inconsistencies. 基于只读操作不会导致不一致的事实, read-write lock为您提供了更大的自由度。 A read-write lock has 3 states: unlocked, read lock, write lock. read-write lock具有3种状态:解锁,读取锁,写入锁。 A write lock works as a regular mutex blocking any other operation. 写锁用作阻止任何其他操作的常规互斥锁。 A read lock on the contrary blocks only write operations. 相反,读锁定仅阻止写操作。

I am not a Java expert but from this answer mutex in Java can be used as the following: 我不是Java专家,但是根据此答案 ,Java中的mutex可以用作以下内容:

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

private final Lock lock = new ReentrantLock(true);
lock.lock()
/*open file and do stuff*/
try {
  // do something
} catch (Exception e) {
  // handle the exception
} finally {
  lock.unlock();
}

Instead here you can find a description of a read-write lock class. 而是在这里可以找到对读写锁类的描述。

From the implementation point of view you can create an instance of one of the two synchronization method and have your read/write thread instances keeping a reference to it, as an instance variable. 从实现的角度来看,您可以创建两个同步方法之一的实例,并使您的读/写线程实例保留对它的引用作为实例变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM