//Tea2.java --- by tsaiwn@csie.nctu.edu.tw
///This example shows you how to resolve the Thread.stop( ) preoblem.
///But, it still hava a problem with concurrent access to same variable n.
///In order to show you the problem, we delay to update the n on purpose.
///The solution to this is to use a synchronized lock to guard it.
public class Tea2 {
    protected static long n = 0;   // n is a shared ticket number
    public static void main(String[ ]args) throws Exception {
        Tea t1sub = new Tea();   // Note that Tea is not a Thread, thus ..
        Thread t1 = new Thread(t1sub);  // We should wrap it as a Thread
        Coffee t2 = new Coffee(); Coffee t3 = new Coffee();
        t1.start(); t2.start(); t3.start();
        while(true){
           try{Thread.sleep(13);}catch(InterruptedException e){;}
           if(n > 10){
              t1sub.shouldDie = true;  // t1.stop();
              t2.shouldDie = true;    // tell the thread to finish it
              t3.shouldDie = true;    // do NOT use stop() to kill it
              break;
           }
        } // while
        t1.join(); t2.join(); t3.join(); // wait for threads to finish up.
        System.out.println("Thank you and Bye!");
    } // main
}
class Coffee extends Thread {
    protected volatile boolean shouldDie = false;
    public void run() {
        long n;
        while(true) {
           n = Tea2.n + 1;   // obtain next ticket number
           System.out.println("Drink Coffee "+ n);
           // yield( );  // yield the CPU right to other threads
           Tea2.n = n;   // write it back to the ticket number
           if(shouldDie) break;
        }
    } // run
} // class Coffee
/// another class which is Runnable. (implements Runnable interface)
class Tea implements Runnable {
    protected volatile boolean shouldDie = false;
    public void run(){
        long n;
        while(true){
           n = Tea2.n + 1;
           System.out.println("Drink Tea "+ n);
           // yield();
           Tea2.n = n;
           if(shouldDie) break;
        }
    } // run
} // class Tea

//
/*** reference result
C:\jsample> javac Tea2.java
C:\jsample> java Tea2
Drink Tea 1
Drink Tea 2
Drink Tea 3
Drink Tea 4
Drink Tea 5
Drink Tea 6
Drink Tea 7
Drink Tea 8
Drink Coffee 8
Drink Coffee 8
Drink Coffee 9
Drink Coffee 9
Drink Coffee 10
Drink Coffee 10
Drink Coffee 11
Drink Coffee 11
Drink Coffee 12
Drink Coffee 12
Drink Coffee 13
Drink Coffee 13
Drink Tea 9
Drink Coffee 14
Drink Tea 10
Drink Coffee 15
Drink Tea 11
Drink Coffee 16
Drink Tea 12
Drink Coffee 17
Drink Tea 13
Drink Coffee 18
Drink Tea 14
Drink Coffee 19
Drink Tea 15
Drink Coffee 14
Drink Tea 16
Drink Coffee 15
Drink Tea 17
Thank you and Bye!

C:\jsample>
*** *** *** *** *** ***/
