IC211 Spring AY 2020

HW More Threads

Name (Last, First): ____________________________________________________ Alpha: _____________________
Describe help received: _________________________________________________________________

HW0.javaQueue.java
public class HW0 {
  public static class QThread extends Thread {
    Queue Q;
    public QThread(Queue Q) {
      this.Q = Q;
    }

    public void run() {
      for( int i = 0; i < 500000; i++ ) {
        Q.enqueue("" + i);
      }

      while( !Q.empty() ) {
        Q.dequeue();
      }
    }
  }
  public static void main(String[] args) {
    Queue Q1 = new Queue();
    Queue Q2 = null;

    if( args.length == 0 ) {
      Q2 = new Queue();
    } else {
      Q2 = Q1;
    }
    Thread t1 = new QThread(Q1);
    Thread t2 = new QThread(Q2);
    t1.start();
    t2.start();
  }
}
public class Queue {
  public synchronized void enqueue(String s) {
    if( head == null ) {
      head = tail = new Node(s, null);
    } else {
      tail.next = new Node(s, null);
      tail = tail.next;
    }
  }

  public synchronized String dequeue() {
    Node t = head;
    head = head.next;

    if( head == null )
      tail = null;

    return t.data;
  }

  public synchronized boolean empty() {
    return head == null;
  }

  private class Node {
    public String data;
    public Node next;
    public Node(String d, Node n) {
      data = d;
      next = n;
    }
  }
  private Node head = null, tail = null;
}

  1. [25pts] Compile the program above, and run it several times like this:
    time java HW0
    and then run it several times like this:
    time java HW0 x
    Compare the "real" times (which is actual seconds passed) for running with and without the commandline argument x (ignoring the crashes that may occasionally occur. Explain why it runs faster without the command-line argument.
  2. [25pts] Continuing with the above program, why does it crash occasionally when run with the command-line argument X?
  3. [10pts] Modify the Queue class (not HW0.java) so that HW0 doesn't crash when run with the command-line argument X. Turn in a codeprint of your modified (and properly commented) Queue.java.
  4. [40pts] Modify the main() below to use Iterators to print out the elements of the TreeSet. You'll want to look at Java API documentation for TreeSet. Turn in a codeprint of your modified (and properly commented) HW1.java along with screenshot of the program running in terminal window.

    HW1.java
    import java.util.*;
    
    public class HW1 {
      public static void main(String[] args) {
        Random rand = new Random(System.currentTimeMillis());
    
        TreeSet<Integer> tr = new TreeSet<Integer>();
    
        for( int i = 0; i < 10; i++ ) {
          tr.add(rand.nextInt(1000));
        }
    
        Iterator<Integer> i;
      }
    }