Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 

Thread example: Simulate multiple readers Java code example - Click here to copy ->>>

   Can't find what you're looking for? Try our search:

Really working examples categorized by API, package, class. You can compile and run our examples right away! Not from source code for Java projects - only working examples! Copy, compile and run!
------------------

/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.com/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*/
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Simulate multiple readers
 @version $Id: ReadersWriterDemo.java,v 1.5 2004/04/26 02:35:51 ian Exp $
 */
public class ReadersWriterDemo {
  private static final int NUM_READER_THREADS = 3;
  public static void main(String[] args) {
    new ReadersWriterDemo().demo();
  }

  /** Set this to true to end the program */
  private boolean done = false;

  /** The data being protected. */
  private BallotBox theData;

  /** The read lock / write lock combination */
  private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

  /**
   * Constructor: set up some quasi-random initial data
   */
  public ReadersWriterDemo() {
    List questionsList = new ArrayList();
    questionsList.add("Agree");
    questionsList.add("Disagree");
    theData = new BallotBox(questionsList);
  }

  /**
   * Run a demo with more readers than writers
   */
  private void demo() {

    // Start two reader threads
    for (int i = 0; i < NUM_READER_THREADS; i++) {
      new Thread() {
        public void run() {
          while(!done) {
            Iterator results = null;
            try {
              lock.readLock().lock();
              results = theData.iterator();
            finally {
              // Unlock in finally to be sure.
              lock.readLock().unlock();
            }
            // Now lock has been freed, take time to print
            print(results);
            try {
              Thread.sleep(((long)(Math.random()1000)));
            catch (InterruptedException ex) {
              // nothing to do
            }
          }
        }
      }.start();
    }
    // Start one writer thread to simulate occasional voting
    new Thread() {
      public void run() {
        while(!done) {
          try {
            lock.writeLock().lock();
            theData.voteFor(
                (((int)(Math.random()*
                theData.getCandidateCount()))));
          finally {
            lock.writeLock().unlock();
          }
          try {
            Thread.sleep(((long)(Math.random()*1500)));
          catch (InterruptedException ex) {
            // nothing to do
          }
        }
      }
    }.start();

    // In the main thread, wait a while then terminate the run.
    try {
      Thread.sleep(10 *1000);
    catch (InterruptedException ex) {
      // nothing to do
    finally {
      done = true;
    }
  }

  /** print the current totals */
  private void print(Iterator iter) {
    boolean first = true;
    while (iter.hasNext()) {
      BallotPosition pair = (BallotPositioniter.next();
      if (!first)
        System.out.print(", ");
      System.out.print(pair.getName() "(" + pair.getVotes() ")");
      first = false;
    }
    System.out.println();
  }


}
/**
* Java Code from Java Cookbook, Second Edition
* By Ian F. Darwin
* Second Edition June 2004
* Series: Cookbooks
* ISBN: 0-596-00701-9
* Details: http://www.oreilly.com/catalog/javacook2/index.html
* Copyright (c) Ian F. Darwin, http://www.darwinsys.com/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*/



References.

The list of classes which were used on this page you can find below. The links to Java API contain official SUN documentation about all used classes.

  java.awt.MediaTracker

  java.util.Set

  java.util.concurrent.locks.ReentrantReadWriteLock

  java.lang.reflect.Constructor

  java.awt.List

  java.util.ArrayList

  java.lang.Thread

  java.util.Iterator

  java.lang.InterruptedException




[ Go Back ]



Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy