Multi-threaded---Reader writer's question

Source: Internet
Author: User
Tags semaphore

There are several ideas
1, using the signal volume to achieve the reader writer's Mutual exclusion (the reader and the reader are parallel)

 Public  class readerandwriter {    Private StaticAtomicinteger reader =NewAtomicinteger ();Private StaticAtomicinteger blocked =NewAtomicinteger ();//used to be mutually exclusive to readers    Private StaticSemaphore ws =NewSemaphore (1,true); Public Static void Main(string[] args) {System.out.println ("Hello world!"); Executorservice executors = Executors.newfixedthreadpool (5); Executors.execute (NewWriterr ()); Executors.execute (NewReaderr (1)); Executors.execute (NewReaderr (2)); Executors.execute (NewReaderr (3)); Executors.execute (NewReaderr (4));    Executors.shutdown (); }StaticClass Writerr implements Runnable { Public void Run(){Try{ while(true) {Ws.acquire (); Write ();//system.out.println ("Waiting:" + ws.getqueuelength () + "-------" +blocked.get ());Ws.release (blocked.get () = =0?1: Blocked.get ()); Blocked.set (0); }            }Catch(Interruptedexception ex) {            }        }Private Static void Write(){Try{System.out.println ("Writing ..."); Thread.Sleep ((NewRandom (). Nextint (2))* +); System.out.println ("writed!"); }Catch(Interruptedexception ex) {            }        }    }StaticClass Readerr implements Runnable {Private intId Public Readerr(intID) { This. id = ID; } Public void Run(){Try{ while(true){if(Reader.get () = =0) {blocked.getandincrement ();                    Ws.acquire (); }//atomically adds 1 to the current valueReader.getandincrement (); Read ();//atomically subtract the current value by 1Reader.getanddecrement ();if(Reader.get () = =0) {ws.release (); }//Sell time, not excessive competition with writer                    //system.out.println ("[" +id+ "] time to sell");Thread.Sleep (6000); }            }Catch(Interruptedexception ex) {            }        }Private void Read(){Try{System.out.println ("["+id +"]reading ..."); Thread.Sleep ((NewRandom (). Nextint (Ten))* +); System.out.println ("["+id+"]read!"); }Catch(Interruptedexception ex) {            }        }    }}

2. Using synchronized to realize the mutual exclusion of readers ' writer

     Public  class ReaderAndWriter1 {     Public StaticFile File =NewFILE (); Public Static void Main(string[] args) {System.out.println ("Hello world!"); Executorservice executors = Executors.newfixedthreadpool (5); Executors.execute (NewWriterr ()); Executors.execute (NewReaderr (1)); Executors.execute (NewReaderr (2)); Executors.execute (NewReaderr (3)); Executors.execute (NewReaderr (4));    Executors.shutdown (); }StaticClass Writerr implements Runnable { Public void Run(){ while(true) {file.write (); }        }    }StaticClass Readerr implements Runnable {Private intId Public Readerr(intID) { This. id = ID; } Public void Run(){Try{ while(true) {File.read (ID);//Sell time, not excessive competition with writer                    //system.out.println ("[" +id+ "] time to sell");Thread.Sleep (6000); }            }Catch(Interruptedexception ex) {}}}}class FILE {//number of readers    Private StaticAtomicinteger reader =NewAtomicinteger (0);//number of written by    Private StaticAtomicinteger writer =NewAtomicinteger (0);//write file     Public void Write(){Try{synchronized(reader) {if(Reader.get () >0) {reader.wait (); }            }synchronized(writer)                {writer.getandincrement (); System.out.println ("Writing ..."); Thread.Sleep ((NewRandom (). Nextint (2))* +); System.out.println ("writed!");                Writer.getanddecrement ();            Writer.notifyall (); }        }Catch(Interruptedexception ex) {        }    }//Read file     Public void Read(intID) {Try{synchronized(writer) {if(Writer.get () >0) {writer.wait ();            }} reader.getandincrement (); System.out.println ("["+id +"]reading ..."); Thread.Sleep ((NewRandom (). Nextint (Ten))* +); System.out.println ("["+id+"]read!"); Reader.getanddecrement ();synchronized(reader) {if(Reader.get () = =0) {reader.notify (); }            }        }Catch(Interruptedexception ex) {        }    }}

3, the concurrent package provides reader writer lock

Readwritelock maintains a pair of related locks, one for read-only operations and the other for write operations. As long as there is no writer, read locks can be persisted by multiple reader threads at the same time. The write lock is exclusive.
Lock Readlock () returns the lock used for the read operation.
Lock Writelock () returns the locks used for write operations

//Very concise program Public  class ReaderAndWriter2 {     Public StaticFile File =NewFILE (); Public Static void Main(string[] args) {System.out.println ("Hello world!"); Executorservice executors = Executors.newfixedthreadpool (5); Executors.execute (NewWriterr ()); Executors.execute (NewReaderr (1)); Executors.execute (NewReaderr (2)); Executors.execute (NewReaderr (3)); Executors.execute (NewReaderr (4));    Executors.shutdown (); }StaticClass Writerr implements Runnable { Public void Run(){ while(true) {file.write (); }        }    }StaticClass Readerr implements Runnable {Private intId Public Readerr(intID) { This. id = ID; } Public void Run(){Try{ while(true) {File.read (ID);//Sell time, not excessive competition with writer                    //system.out.println ("[" +id+ "] time to sell");Thread.Sleep (6000); }            }Catch(Interruptedexception ex) {            }        }    }}//File classClass FILE {//Using the read-write lock in the Concurrent toolkit    Private StaticReadwritelock lock =NewReentrantreadwritelock ();//write lock    Private StaticLock write = Lock.writelock ();//Read lock    Private StaticLock read = Lock.readlock ();//write Operation     Public Static void Write(){Try{Write.lock (); System.out.println ("Writing ..."); Thread.Sleep (NewRandom (). Nextint (3)* +); System.out.println ("writed! "); }Catch(Interruptedexception ex) {        }finally{Write.unlock (); }    }//Read operation     Public Static void Read(intID) {Try{Read.lock (); System.out.println ("["+id+"]reading ..."); Thread.Sleep (NewRandom (). Nextint (5)* +); System.out.println ("["+id+"]read! ");//Time to sellThread.Sleep (6000); }Catch(Interruptedexception ex) {        }finally{Read.unlock (); }    }}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Multi-threaded---Reader writer's question

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.