Home   Cover Cover Cover Cover
 

Print server

Chap4_Ex10.cs
using System;
using System.Threading;
using System.Collections;

/** A printjob
 */
public class Job {
  private string name;
  private int pages;

  public Job(string n, int p) {
    this.name = n;
    this.pages = p;
  }

  public string Name {
    get { return name; }
    set { name = value; }
  }

  public int Pages {
    get { return pages; }
    set { pages = value; }
  }
}

public class PrintServer {
  public static int MINDELAY = 500;
  public static int RANDELAY = 1000;
  public static int MAXPAGES = 50;
  private Queue q;
  private Thread t;
  private bool running = true;

  public PrintServer() {
    q = new Queue();
  }

  public void Start() {
    t = new Thread(new ThreadStart(GenerateRandomJobs));
    t.Start();
  }

  public void AddJob(Job j) {
    Monitor.Enter(q);
    q.Enqueue(j);
    Console.WriteLine("Job: {0} with pages: {1} added to the queue", j.Name, j.Pages);
    Monitor.PulseAll(q);
    Monitor.Exit(q);
  }

  public Job GetNextJob() {
    Monitor.Enter(q);
    while(q.Count==0) Monitor.Wait(q);
    Job j = (Job) q.Dequeue();
    Monitor.PulseAll(q);
    Monitor.Exit(q);
    Console.WriteLine("Job: {0} with pages: {1} removed from the queue", j.Name, j.Pages);
    return j;
  }

  public void GenerateRandomJobs() {
    int nr = 0;
    while(running) {
      System.Random r = new Random(DateTime.Now.Millisecond);
      Job j = new Job("jobNr_"+nr, r.Next(MAXPAGES));
      this.AddJob(j);
      nr++;
      Thread.Sleep(MINDELAY+r.Next(RANDELAY));
    }
  }

  public bool Running {
    get { return running; }
    set { running = value; }
  }  
}

public class Cap4_Ex10_Test {

  public static void Main(string[] args) {
    PrintServer ps = new PrintServer();
    ps.Start();
    // processing of print jobs
    while(true) {
      Job j = ps.GetNextJob();
      Thread.Sleep(j.Pages*20);
    }
  }
}