-java realization of reader-writer problem

Source: Internet
Author: User
Tags semaphore

Reader-writer problem (Readers-writers problem) is also a classic concurrent programming problem, which is often a synchronization problem. Data (Files, records) in a computer system are often shared by multiple processes, but some of these processes may require only read data (called Reader readers), while others require the modification of data (called writer writers). In terms of shared data, reader and writer are two sets of concurrent processes that share a set of data areas that require:
(1) Allow multiple readers to perform read operations at the same time;
(2) The reader and the writer are not allowed to operate at the same time;

(3) Not allow multiple writes to operate simultaneously.

The principle of implementation:

The simple use of semaphores does not solve the reader and writer problems, the counter readcount must be introduced to the reading process count; Readcountsemophore is a mutually exclusive semaphore used for counter readcount operations. The signal is introduced to ensure atomic operation (in fact, Java has a keyword synchronized can implement the atomic operation of the block, to ensure that only one thread to manipulate the block, in fact, this keyword is encapsulated signal volume). Write indicates whether to allow the volume of the write, so the reader first programming principle is as follows:

Readers:

while (true)

P (RCS);

     if (rc==0)

    {

          rc++;

          P (write);

   }

   v (RCS);

//read data

  P (RCS)

   rc--;

    if (rc==0)

         v (write);

V (RCS)

Written by:

while (true)

{

P (write);

Write and write

V (write);

}

Java implementations:

Readers:

Import Java.util.random;import Java.util.concurrent.semaphore;public class Readthread extends Thread{public int id;// Reader Idpublic int readcount;//reader number public Semaphore readcountsemaphore;//number of readers semaphore public Semaphore writesemaphore;// Writer Semaphore public Readthread (int id, int rcount, Semaphore semaphore,semaphore semaphore2) {this.id = Id;this.readcount = Rcount This.readcountsemaphore = Semaphore;this.writesemaphore=semaphore2;this.start ();//start reading}//reader priority public void run () {try {//No one is writing if (Writesemaphore.availablepermits () >0)//can read System.out.println ("reader" +id+ "can read ..."); else { System.out.println ("Writer in writing operation, reader" +id+ "waiting to read ..."); Waiting to read readcountsemaphore.acquire (); if (Readcount = = 0)//If the first reader, then to consider whether there is a writer, no writer, direct reading, there is a writer, waiting for the writer {//At this time can not write READC ount++;//already has the condition of reading, the number of readers plus 1writesemaphore.acquire ();} Readcountsemaphore.release ();/**********************************///can now allow other readers to read the data/**************************** /readcountsemaphore.acquire ();//Can read System.out.println ("reader" +id+ "I am reading Oh ..."); Thread.Sleep ((Long) (newRandom (). Nextfloat () *2000)); System.out.println ("Reader" +id+ "read ...");//Read, the number of readers decreased 1readcount--;if (readcount==0)//No reader, you can write { Writesemaphore.release ();} Readcountsemaphore.release ();//Release Reader semaphore}catch (interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}

Written by:

Import Java.util.random;import Java.util.concurrent.semaphore;public class Writethread extends thread{public   int id;//number public   Semaphore writesemaphore;//writer Semaphore public   writethread (int id,semaphore Semaphore)   {   This.id=id;   This.writesemaphore=semaphore;   This.start ();   }   public void Run ()   {   try{if (writesemaphore.availablepermits () >0) {System.out.println ("writer" +this.id+ "can write "); } Else System.out.println ("writer" +this.id+ "cannot be written"); Writesemaphore.acquire (); System.out.println ("writer" +this.id+ "writing ..."); Thread.Sleep ((Long) (New Random (). Nextfloat () *2000)); System.out.println ("writer" +this.id+ "finished ..."); Writesemaphore.release ();} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}   

Main program:

Import Java.util.random;import Java.util.concurrent.semaphore;public class readandwrite{public static final int count= 10;//number of readers written/** * @param args */public static void main (string[] args) {//TODO auto-generated method Stubsemaphore Readcou Ntsemaphore=new Semaphore (1); Semaphore writesemaphore=new Semaphore (1); int readcount=0;        for (int i=0;i<count;i++)        {        //randomly generate reader and writer        if (new random (). Nextboolean ())//Assume that the reader is        new Readthread (I, Readcount, Readcountsemaphore, writesemaphore);        else {new Writethread (I, Writesemaphore);}}}}        

Operating effect:

      

-java realization of reader-writer problem

Related Article

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.