一旦一个线程处于Runnable状态,它就会连续地执行,直到run()方法结束。Thread早期版本中有一个stop()方法,可以随时终止线程的执行。由于stop()方法在JDK的较新版本中已建议不再使用。因此,要使用一些技巧来实现这一手段。就我目前接触到的来看,要分两种情况:
1.对于继承Thread类构造线程的情况
1 public class ClassName extends Thread 2 { 3 private boolean running=false; 4 //该类的域和方法 5 //一般包含如下start()方法用于启动线程
6 public void start() 7 { 8 running=true; 9 super.start(); 10 } 11 //一般包含如下halt()方法用于终止线程
12 public void halt() 13 { 14 running=false; 15 } 16 //在run()方法中使用类似于下例的while循环
17 public void run() 18 { 19 while(running) 20 { 21 /*线程要执行的代码*/
22 } 23 } 24
25 }
2.对于实现Runnable接口构造线程的情况
注意,下面的stop()和start()方法不是自动被调用的,它们仅提供一种很方便的手段去终止或者启动线程。
1 public class ClassName extends Thread 2 { 3 private Thread threadName=null; 4 //该类的域和方法 5 //一般包含如下start()方法用于启动线程
6 public void start() 7 { 8 if(threadName==null) 9 { 10 threadName=new Thread(this); 11 threadName.start(); 12 } 13 } 14 //一般包含如下stop()方法用于终止线程
15 public void stop() 16 { 17 threadName=null; 18 } 19 //在run()方法中使用类似于下例的while循环
20 public void run() 21 { 22 Thread currentThread=Thread.currentThread(); 23 while(threadName==currentThread) 24 { 25 /*有适当的代码调用threadName.sleep(sleeptime)或者threadName.yied()*/
26 } 27 } 28
29 }
Notice:
如果while循环中还使用了循环,此时调用自定义的halt()或者stop()方法可能不能立即终止线程,而是会运行到while循环中的循环结束为止。