zoukankan      html  css  js  c++  java
  • java如何停止一个运行的线程?

    关于线程的一点心得

    //首先导入需要的包

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

      }
    }

    个人经验,不足之处望指出。

  • 相关阅读:
    CF1480
    网络编程中常见地址结构与转换(IPv4/IPv6)
    inet_pton, inet_ntop
    mktime 夏令时
    C/C++中volatile关键字详解
    STL之vector容器详解
    Linux学习--gdb调试
    Linux编程基础——GDB(设置断点)
    FTP模式简式:PORT/PASV/EPRT/EPSV
    strchr和strstr 函数
  • 原文地址:https://www.cnblogs.com/lq147760524/p/java-stopThread.html
Copyright © 2011-2022 走看看