0

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。并且这段代码是否有地方缺失吗

2018-02-15 提问

查看全部 2 个回答

0

从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;
    }
}

推荐答案

1

楼上的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;
    }

你可能感兴趣的

推广链接