[Java] java 停止线程 →→→→→进入此内容的聊天室

来自 , 2019-11-18, 写在 Java, 查看 107 次.
URL http://www.code666.cn/view/185c29dc
  1. /**
  2.  * 停止线程
  3.  */
  4. public class StopThread {
  5.         /** 线程对象 */
  6.         private ThreadA thread = new ThreadA();
  7.  
  8.         /** 自定义线程类 */
  9.         class ThreadA extends Thread {
  10.                 // 用一个boolean值标记线程是否需要运行。
  11.                 private boolean running = false;
  12.  
  13.                 // 覆盖了父类的start方法,
  14.                 public void start() {
  15.                         // 将running置为ture,表示线程需要运行
  16.                         this.running = true;
  17.                         super.start();
  18.                 }
  19.  
  20.                 public void run() {
  21.                         System.out.println("ThreadA begin!");
  22.                         int i = 0;
  23.                         try {
  24.                                 // 如果running为真,说明线程还可以继续运行
  25.                                 while (running) {
  26.                                         System.out.println("ThreadA: " + i++);
  27.                                         // sleep方法将当前线程休眠。
  28.                                         Thread.sleep(200);
  29.                                 }
  30.                         } catch (InterruptedException e) {
  31.                         }
  32.  
  33.                         System.out.println("ThreadA end!");
  34.                 }
  35.  
  36.                 public void setRunning(boolean running) {
  37.                         this.running = running;
  38.                 }
  39.         }
  40.  
  41.         /**
  42.          * 启动ThreadA线程
  43.          */
  44.         public void startThreadA() {
  45.                 System.out.println("To start ThreadA!");
  46.                 thread.start();
  47.         }
  48.  
  49.         /**
  50.          * 停止ThreadA线程
  51.          */
  52.         public void stopThreadA() {
  53.                 System.out.println("To stop ThreadA!");
  54.                 thread.setRunning(false);
  55.         }
  56.  
  57.         public static void main(String[] args) {
  58.                 StopThread test = new StopThread();
  59.                 // 启动ThreadA线程
  60.                 test.startThreadA();
  61.                 // 当前线程休眠一秒钟
  62.                 try {
  63.                         Thread.sleep(1000);
  64.                 } catch (InterruptedException e) {
  65.                         e.printStackTrace();
  66.                 }
  67.                 // 停止ThreadA线程
  68.                 test.stopThreadA();
  69.         }
  70. }
  71.  

回复 "java 停止线程"

这儿你可以回复上面这条便签

captcha