java如何停止一個啟動並執行線程?

來源:互聯網
上載者:User

標籤:心得   輸出   schedule   java   線程   sleep   new t   for   import   

關於線程的一點心得

//首先匯入需要的包

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("異常");
    }

  }
}

 

個人經驗,不足之處望指出。

java如何停止一個啟動並執行線程?

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.