Multithreading--reader Writer's question

Source: Internet
Author: User

Solution One:
Mutual exclusion between reader and writer (semaphore)
The reader is in parallel (if a reader is reading it, the reader can read it without having to apply for permission)

 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) {            }        }    }}

Solution Two:
Lock with synchronized

 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) {        }    }}

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

Multithreading--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.