Java - Start and Stop a Thread

  1. package javaapplication1; 
  2. public class Main 
  3.     public static void main(String[] args) throws Exception 
  4.     { 
  5.         Runner mRunner = new Runner(); 
  6.         // Allocates a new Thread object. 
  7.         // mRunner - the object whose run method is called. 
  8.         // start() - causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread. 
  9.         new Thread(mRunner).start(); 
  10.         for (int i = 0; i < 1000; i++) 
  11.         { 
  12.             System.out.println("     ------" + Thread.currentThread()); 
  13.         } 
  14.         // Set message to stop the thread. 
  15.         mRunner.makeStop(); 
  16.     } 
  17. // The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. 
  18. class Runner implements Runnable 
  19.     boolean makeStop = false
  20.     @Override 
  21.     public void run() 
  22.     { 
  23.         while (true
  24.         { 
  25.             System.out.println("++++++      " + Thread.currentThread()); 
  26.             if (makeStop == true
  27.             { 
  28.                 return
  29.             } 
  30.         } 
  31.     } 
  32.     public void makeStop() 
  33.     { 
  34.         this.makeStop = true
  35.     } 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章