UNIVERSITY OF WISCONSIN-MADISON
Computer Sciences Department
CS 537
Spring 2001
A. Arpaci-Dusseau
Quiz #1: Jan 31, 2001 -- Solutions

Consider the following Java program, with two classes. The system can switch between threads at anytime, generating many possible outputs. For each of the outputs on the next page, indicate whether it could or could not have been generated by the program.

public class Quiz1 {
    public static a = 0;
    public static void main(String argv[]) {

    Command cmd1 = new Command("ABCDEF");
    Thread t1 = new Thread (cmd1);
    System.out.println("Created thread 1");

    Command cmd2 = new Command("abcdef");
    Thread t2 = new Thread (cmd2);
    System.out.println("Created thread 2");

    Command cmd3 = new Command("012345");
    Thread t3 = new Thread (cmd3);
    System.out.println("Created thread 3");

    t1.start();
    t2.start();
    t3.start();

    try { t1.join(); } catch (InterruptedException e)
    { System.out.println("Join interrupted"); }
    System.out.println("Thread 1 died");

    try { t2.join(); } catch (InterruptedException e)
    { System.out.println("Join interrupted"); }
    System.out.println("Thread 2 died");

    try { t3.join(); } catch (InterruptedException e)
    { System.out.println("Join interrupted"); }
    System.out.println("Thread 3 died");
    }
}
class Command implements Runnable {
    private String s;
    Command(String str) { s = str; }
    public void run() {
        System.out.println(s);
        Quiz1.a++;
        System.out.println(Quiz1.a);
    }
}

Yes, possible
Created thread 1
Created thread 2
Created thread 3
ABCDEF
1
abcdef
2
012345
3
Thread 1 died
Thread 2 died
Thread 3 died
Yes, possible
Created thread 1
Created thread 2
Created thread 3
012345
1
abcdef
2
ABCDEF
3
Thread 1 died
Thread 2 died
Thread 3 died
No, not possible
Created thread 3
Created thread 2
Created thread 1
ABCDEF
1
abcdef
2
012345
3
Thread 1 died
Thread 2 died
Thread 3 died
No, not possible
Created thread 1
Created thread 2
Created thread 3
ABCDEF
1
abcdef
2
012345
3
Thread 3 died
Thread 2 died
Thread 1 died
Yes, possible
Created thread 1
Created thread 2
Created thread 3
ABCDEF
1
Thread 1 died
abcdef
2
Thread 2 died
012345
3
Thread 3 died
No, not possible
Created thread 1
ABCDEF
1
Created thread 2
abcdef
2
Created thread 3
012345
3
Thread 1 died
Thread 2 died
Thread 3 died
No, not possible
Created thread 1
ABCDEF
1
Thread 1 died
Created thread 2
abcdef
2
Thread 2 died
Created thread 3
012345
3
Thread 3 died
No, not possible
Created thread 1
Created thread 2
Created thread 3
ABCDEF
3
abcdef
3
012345
3
Thread 1 died
Thread 2 died
Thread 3 died