//TestTea.java --- by tsaiwn@csie.nctu.edu.tw ///This program demostrates how to use Thread in Java. ///But there are two problems: ///(1) stop() is unsafe. This might crash the program.(多 Run 幾次試試) /// We should tell thread to die by using a flag instead of /// using stop( ) to kill the thread. ///(2)concurrent access to TestTea.n might cause synchronization problem. /// Codes access to the same variable should be monitored by using /// a synchronized block to mark as a Critical Section. public class TestTea { protected static long n = 0; public static void main(String[]x) throws Exception{ Tea t1 = new Tea(); Coffee t2 = new Coffee(); t1.start(); t2.start(); while(true){ Thread.sleep(13); if(n > 10){ t1.stop(); t2.stop(); break; } } // while System.out.println("Thank you and Bye!"); } } class Coffee extends Thread{ public void run(){ while(true){ System.out.println("Drink Coffee "+ ++TestTea.n); // yield(); } } // run } class Tea extends Thread{ public void run(){ while(true){ System.out.println("Drink Tea "+ ++TestTea.n); // yield(); } } // run }