ReadWriteLock用于防止异常吗?哪一个?

时间:2018-05-18 20:02:19

标签: java multithreading io

我同时从多个线程读取/写入一个文件,而不同步 Reader Writer 。然而,没有例外被抛出。

用于防止异常的 ReadWriteLock 吗?

public class Main {
    public static void main(String[] args) {
        int nmbOfThreads = 10;
        int nmbOfReadWritePerThread = 100;
        int maxWaitTimeBetweenReadWrite = 3; // seconds
        try {
            File f = new File("C:\\tmp\\foo.txt");
            Writer wrtr = new FileWriter(f);
            Reader rdr = new FileReader(f);

            Set<Thread> threads = new HashSet();        
            for(int i = 0; i < nmbOfThreads; i++) {                
                Thread t = new Thread(new Worker(rdr, wrtr, nmbOfRdWrtPerThread, maxWaitTimeBetweenReadWrite));                
                threads.add(t);
            }

            for(Thread t : threads) { t.start(); }     
            for(Thread t : threads) { t.join(); }        
            wrtr.close();    
            rdr.close();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    static void rndmPause(int range) throws Exception {
        long milliSec = (long) new Random(System.currentTimeMillis()).nextLong();
        milliSec = (long) (Math.abs(milliSec) % (range * 1000));
        Thread.sleep((long) milliSec);
    }


         static class Worker implements Runnable {
             Reader rdr; Writer wrtr;
             int nmbRdWrt, maxWaitTime;

             public Worker(Reader rdr, Writer wrtr, int nmbRdWrt, int maxWaitTime) {
                 this.rdr = rdr;
                 this.wrtr = wrtr;
                 this.nmbRdWrt = nmbRdWrt;
                 this.maxWaitTime = maxWaitTime;
             }

             public void run() {
                 try {
                     for(int i = 0; i < nmbRdWrt; i++) {
                         rndmPause(maxWaitTime);
                         wrtr.write("foo" + System.getProperty("line.separator"));
                         wrtr.flush();

                         rndmPause(maxWaitTime);
                         char[] cbuf = new char[100];
                         rdr.read(cbuf);
                     }
                 } catch(Exception e) {
                     e.printStackTrace();
                 }      
             }                  
         }
     }
}

或者, ReadWriteLock 是否仅用于防止多个线程相互踩踏并写入乱码文本?

1 个答案:

答案 0 :(得分:0)

ReadWriteLock不仅用于防止异常,还要确保writer无法在其他writerreader存在的情况下进行写入。 你是如何处理这种情况的?

看看

class Main {
    private static volatile int numFileWriter = 0;
    public static void main(String[] args) {
        int nmbOfThreads = 100;
        int nmbOfReadWritePerThread = 100;
        int maxWaitTimeBetweenReadWrite = 1; // seconds
        try {
            File f = new File("/home/mwalko/test");
            Writer wrtr = new FileWriter(f);
            Reader rdr = new FileReader(f);

            Set<Thread> threads = new HashSet();
            for(int i = 0; i < nmbOfThreads; i++) {
                Thread t = new Thread(new Worker(rdr, wrtr, nmbOfReadWritePerThread, maxWaitTimeBetweenReadWrite, i));
                threads.add(t);
            }

            for(Thread t : threads) { t.start(); }
            for(Thread t : threads) { t.join(); }
            wrtr.close();
            rdr.close();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    static void rndmPause(int range) throws Exception {
        long milliSec = (long) new Random(System.currentTimeMillis()).nextLong();
        milliSec = (long) (Math.abs(milliSec) % (range * 1000));
        Thread.sleep((long) milliSec);
    }


    static class Worker implements Runnable {
        Reader rdr; Writer wrtr;
        int nmbRdWrt, maxWaitTime, threadNumber;

        public Worker(Reader rdr, Writer wrtr, int nmbRdWrt, int maxWaitTime, int threadNumber) {
            this.rdr = rdr;
            this.wrtr = wrtr;
            this.nmbRdWrt = nmbRdWrt;
            this.maxWaitTime = maxWaitTime;
            this.threadNumber = threadNumber;
        }

        public void run() {
            try {
                for(int i = 0; i < nmbRdWrt; i++) {
                    rndmPause(maxWaitTime);
                    wrtr.write("foo thread: " + threadNumber + " num: " + numFileWriter + System.getProperty("line.separator"));
                    wrtr.flush();
                    numFileWriter++;
                    rndmPause(maxWaitTime);
                    char[] cbuf = new char[100];
                    rdr.read(cbuf);
                }
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
    }
}

文件中的结果:

foo thread: 33 num: 0
foo thread: 99 num: 0
foo thread: 29 num: 0
foo thread: 39 num: 0
foo thread: 7 num: 0
foo thread: 98 num: 0
foo thread: 95 num: 0
foo thread: 20 num: 0
foo thread: 75 num: 0
foo thread: 58 num: 0
foo thread: 47 num: 0
foo thread: 67 num: 0
foo thread: 40 num: 0
foo thread: 37 num: 0
foo thread: 21 num: 0
foo thread: 74 num: 0
foo thread: 16 num: 0
foo thread: 0 num: 0
foo thread: 70 num: 0
foo thread: 73 num: 19
foo thread: 63 num: 19
foo thread: 38 num: 20

当你同步它或使用ReadWriteLock或使用BufferedWriter(线程安全)时,结果可能是正确的。正确我的意思是numFileWriter状态良好