/* Three independent threads which yield after each output statement
*
* 1. Thread one prints the letter 'a' 10 times.
* 2. Thread two prints the letter 'b' 10 times.
* 3. Thread three prints the integers 1 through 10.
*/
public class TestYield {
    // main method
    public static void main(String args[]) {

        // If there are cmd line args, the threads won't yield
        boolean yield = args.length > 0 ? false : true;

        // Create threads
        PrintChar printA = new PrintChar('a', 10, yield);
        PrintChar printB = new PrintChar('b', 10, yield);
        PrintNum print10 = new PrintNum(10, yield);

        // Start threads
        printA.start();
        printB.start();
        print10.start();

    } 
} 

class PrintChar extends Thread {
    private char charToPrint; // the character to print
    private int times; // The times to repeat
    private boolean yield; // Do I yield?
    
    // Construct a thread with specified character and number
    // of times to print the character
    public PrintChar(char c, int t, boolean y) {
        charToPrint = c;
        times = t;
        yield = y;
    } 

    // Override the run() method to tell the system
    // what the thread will do
    public void run() {
        for (int i=0; i < times; i++) {
            System.out.print(" " + charToPrint);
            
            // Let other threads run if told to
            if (yield) {
                Thread.yield();
            }
        }
    }
} 

class PrintNum extends Thread {
    private int lastNum; // the last number to print
    private boolean yield; // Do I yield?

    // Construct a thread with the last number
    public PrintNum(int n, boolean y) {
        lastNum = n;
        yield = y;
    } 

    // Override the run() method to tell the system
    // what the thread will do
    public void run() {
        for (int i=0; i<=lastNum; i++) {
            System.out.print(" " + i);

            // Let other threads run if told to
            if (yield) {
                Thread.yield();
            }
        }
    } 
} 

