java thread 问题

新手上路,请多包涵

public class TestMain {

public static void main (String args[]) {
  LoopCountThread loopCountThread;                
  loopCountThread = new LoopCountThread();  
  loopCountThread.start();                  
  try { System.in.read();

} catch(java.io.IOException e) {

   e.printStackTrace();
  }
  loopCountThread.stop();}

}

class LoopCountThread extends Thread {
public void run() {

  int Count = 0;
  while (true) 
  {
    System.out.println("running, iCount = " + Count++);   
      try {Thread.sleep(1000);}                         
      catch(InterruptedException e){}
  }

}
}

源代码 显示stop方法 deprecated。并且这段代码是否有地方缺失吗

阅读 2.1k
2 个回答

楼上的on没用到循环判断条件上,更正一下~

public class TestMain {
    public static void main(String[] args) {
        LoopCountThread loopCountThread= new LoopCountThread();
        Thread countThread = new Thread(loopCountThread,"CountThread");
        countThread.start();
        try {
            System.in.read();
        } catch (Exception e) {

            e.printStackTrace();
        }
        loopCountThread.cancel();
    }
}

class LoopCountThread implements Runnable {
    private  long Count = 0;
    private volatile boolean on = true;
    public void run() {

        while (on) {
            System.out.println("running, iCount = " + Count++);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
        }
    }
    public  void cancel() {

        on = false;
    }

从J2SE 1.2就废弃了,以后尽量不要用stop()、suspend、resume。
尽量实现Runnable接口创建线程。 你那死循环,,我就不改了


代码用这种格式包起来:
-         ```java
            code
-         ```

/**
 * Created by guo on 2018/2/15.
 */
public class TestMain {
    public static void main(String[] args) {
        LoopCountThread loopCountThread= new LoopCountThread();
        Thread countThread = new Thread(loopCountThread,"CountThread");
        countThread.start();
        try {
            System.in.read();
        } catch (Exception e) {

            e.printStackTrace();
        }
        loopCountThread.cancel();
    }
}

class LoopCountThread implements Runnable {
    private  long Count = 0;
    private volatile boolean on = true;
    public void run() {

        while (true) {
            System.out.println("running, iCount = " + Count++);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
        }
    }
    public  void cancel() {

        on = false;
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题