關於線程的一點心得
//首先導入需要的包
improt java.util.Timer;
import java.io.File;
import java.util.TimerTask;
//首先需要創建一個線程並且一直運行,然后創建一個計時器任務來觸發事件(比如創建一個stop.txt文件,如果發現文件存在則停止運行程序)。
public class Stop{
public static void main(String args[]){
//創建線程,運行。
Count cou=new Count(true);
Thread th=new Thread(cou);
th.start();
//創建一個計時器任務
Timer time=new Timer();
//使用匿名內部類啟動計時任務,如果發現文件stop.txt則停止上面線程。
time.schedule(new TimerTask(){
public void run(){
File file=new File("stop.txt");
if(file.exists()){
Count.setFlag(false);
System.exit(-1);
}
},100,1000);
}
}
//通過Runnable接口來創建線程,創建一個boolean flag變量來標記運行狀態。
class Conunt implements Runnable{
private boolean flag;
public Count(boolean flag){
this.falg=flag;
}
public void setFlag(boolean flag){
this.falg=flag;
}
//重寫Runnable接口的抽象方法,讓程序每隔一秒鍾輸出一個線程狀態數字。
public void run(){
for(int i=0;flag;i++){
try{
Thread.sleep(1000);
System.out.println(Thread.cuurentThread().getName()+i);
}catch{
System.out.println("異常");
}
}
}
個人經驗,不足之處望指出。