Spring 2001, CSE 428: Quiz 6.3 - 1 March 2001


Please write your Name and Student ID,at the top of the page.
By default, this quiz will be returned in Section 1 (afternoon section). If you want to get it back in the morning section, please write "Section 2" at the top of the page.
Consider the following declaration in Java, where myRandom() is a function which returns an arbitrary number. Ignore the problem of InterruptedException in the instruction sleep.
class Foo{
   private int content;
   private String name;

   public Foo(String s){ content = 0; name = s; }
   public void addContent(int k) { content = content + k; }
   public void printContent() { System.out.print(content+" "); }
   public void printName() { System.out.print(name+" "); }
}

class MyThread extends Thread{
   private Foo f;
           
   public MyThread(Foo f){ this.f = f; }
   public void run(){ 
      sleep(myRandom());    //Sleep an arbitrary amount of time. 
      f.printName();        //Print the name of f
      sleep(myRandom());    //Sleep an arbitrary amount of time. 
      f.addContent(1);      //Update the content of f
      sleep(myRandom());    //Sleep an arbitrary amount of time. 
      f.printContent();     //Print the content of f
    }
}

      ...
   public static void main(String[] args) {
      Foo f = new Foo("Giorgio");
      MyThread T1 = new MyThread(f);
      MyThread T2 = new MyThread(f);
      T1.start(); 
      T2.start();
   }
  1. [Pts 4]  For each of the following methods, specify whether it needs to be synchronized or not

  2. [Pts 2]  In a given execution, how many times will the name "Giorgio" be printed?  
     
    2  

  3. [Pts 4]  Suppose you have added the synchronization keyword on all the methods of Foo except the constructor. For each of the following ouptut sequences, say whether or not it can be obtained by executing the program.