在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Java/ java thread 問題

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。并且這段代碼是否有地方缺失嗎

回答
編輯回答
涼心人

從J2SE 1.2就廢棄了,以后盡量不要用stop()、suspend、resume。
盡量實現(xiàn)Runnable接口創(chuàng)建線程。 你那死循環(huán),,我就不改了


代碼用這種格式包起來:
-         ```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;
    }
}
2017年10月23日 17:56
編輯回答
葬愛

樓上的on沒用到循環(huán)判斷條件上,更正一下~

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;
    }
2017年10月15日 03:26