import java.io.*;
public class controlThread {
/**
* @param args
*/
public static void main(String[] args) {
try {
test t=new test();
System.out.println("心算遊戲/n/n輸入回車開始計時");
new InputStreamReader(System.in).read();
t.start();
new InputStreamReader(System.in).read();
t.stopme();
} catch (IOException e) {}
}
}//controlThread
class test extends Thread
{
int i=0;
boolean flag=true;
public void run()
{while(flag)
try {
i++;
Thread.sleep(1000);
} catch (InterruptedException e) {}
}
public void stopme()
{ flag=false;
System.out.println("共過了"+i+"秒,跟你的心算一樣嗎?");}
}//test
/*
學習心得:
1.Thread類的stop()方法可以結束線程的生命,但如果一個線程正在操作共享數據段,操作過程沒有完就用stop結
束,會導致數據不完整,因此並不提倡使用此方法。
2.比較安全的方法是通過控制run()方法的循環條件來結束一個線程,上例通過輸入回車調用一個stopme()
方法來講循環條件設爲false
*/