首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ReadWriteLock是否用于防止异常?哪个?

ReadWriteLock是否用于防止异常?哪个?
EN

Stack Overflow用户
提问于 2018-05-18 20:02:18
回答 1查看 125关注 0票数 0

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

ReadWriteLock是否用于防止异常?

代码语言:javascript
复制
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是否仅用于防止多个线程之间的践踏和写错的文本?

EN

回答 1

Stack Overflow用户

发布于 2018-05-18 20:22:50

ReadWriteLock不仅用于防止异常,还可以确保在任何其他writerreader已经存在的情况下,writer不会访问写入。你如何处理这种情况?

瞧一瞧

代码语言:javascript
复制
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();
            }
        }
    }
}

文件中的结果:

代码语言:javascript
复制
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井井有条

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50418509

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档