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

Java ReadWriteLock是否用于防止异常?哪一个?,java,multithreading,io,Java,Multithreading,Io,我同时从多个线程读/写一个文件,读写器不同步。但没有抛出任何异常 ReadWriteLock是否用于防止异常 public class Main { public static void main(String[] args) { int nmbOfThreads = 10; int nmbOfReadWritePerThread = 100; int maxWaitTimeBetweenReadWrite = 3; // seconds

我同时从多个线程读/写一个文件,读写器不同步。但没有抛出任何异常

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();
                 }      
             }                  
         }
     }
}
公共类主{
公共静态void main(字符串[]args){
int nmbOfThreads=10;
int nmbOfReadWritePerThread=100;
int maxWaitTimeBetweenReadWrite=3;//秒
试一试{
文件f=新文件(“C:\\tmp\\foo.txt”);
Writer wrtr=新文件编写器(f);
读卡器rdr=新文件读卡器(f);
Set threads=newhashset();
对于(inti=0;i

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

ReadWriteLock不仅用于防止异常,还用于确保当任何其他
写入程序或
读取程序已经存在时,
写入程序
无法访问写入。 你如何处理这种情况

看一看

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();
            }
        }
    }
}

当您同步它或使用ReadWriteLock或使用BufferedWriter(线程安全)时,结果可能是正确的。我所说的“正确”是指顺序良好的
numFileWriter
,实际上我想抛出一个异常。如何使我的并发读/写文件抛出异常?你可以调用锁上的
tryLock()
,如果失败则抛出。你说“当然它是在防止异常”。好的,这个异常的名称是什么?@LouisWasserman我现在知道了。除了修改交互集合之外,测试线程安全性是一个巨大的挑战。它用于确保并发条件下的正确性。@EJP我想我明白了。“ConcurrentModificationException”仅在集合的某些情况下发生。在大多数情况下,测试某些东西是否“线程安全”并不容易!
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