ThreadPlay

Play around with this program and see what is going on. Update the program so if the word yield is passed in as a command-line argument, the threads will yield.

You may work with a partner on this part; run it a number of times to get "weird" behavior. Answer the following questions:

  1. What kind of scheduler do you have on your system and how you know this?
  2. What is going on with the yield? Are the threads guaranteed to alternate? Why or why not?
  3. What else do you notice?
  4. Pick one run with strange behavior and explain it using the thread states.
Email your code and with the explanations and one weird test run to the course email account before class on Thursday. Please put ThreadPlay in the subject line.
// Make sure you add your name(s), command-line arguments, and answer the questions!

public class ThreadPlay
{
public static void main (String args[])
{
    MyThread threadObj = new MyThread();

    new Thread(threadObj,"Dog").start();
    new Thread(threadObj,"Cat").start();
}
}

public class MyThread implements Runnable
{
private int _max = 20;
private int _count = 0;
private int _x;
private int _y;
private boolean yield = false;

public void setXandY(int x, int y)
{
    _x = x;
    //pause(100);
    _y = y;
}
public void run()
{
    String msg;
    msg = Thread.currentThread().getName();

    while (_count < _max)
    {
        setXandY(_count, _count + 1);
        System.out.println(Thread.currentThread().getName()
            + " _count is " + _count + " x is " + _x
            + " y is " + _y);

        _count++;

        if (yield)
        {
            System.out.println(Thread.currentThread().getName() + " yielding");
            Thread.yield();
        }
    }

    msg = msg + " count: " + _count  + " max: " + _max;
    System.out.println(Thread.currentThread().getName() + " says bye-bye! " + msg);
}
void pause(int milliseconds)
{
    try
    {
        Thread.sleep(milliseconds);
    }
    catch (InterruptedException e) {}
}
}