一种是调用它里面的stop()方法
另一种就是你自己设置一个停止线程的标记 (推荐这种)
代码如下:
package com.demo
//测试Thread的stop方法和自己编写一个停止标记来停止线程
public class StopThread implements Runnable{
//停止线程的标记值boolean
private boolean flag = true
public void stopThread(){
flag = false
}
public void run(){
int i=0
while(flag){
i++
System.out.println(Thread.currentThread().getName()+":"+i)
try{
Thread.sleep(1000)
}catch(Exception e){
}
System.out.println(Thread.currentThread().getName()+"==>"+i)
}
}
public static void main(String args[]){
StopThread st = new StopThread()
Thread th = new Thread(st)
Thread th1 = new Thread(st)
th.start()
th1.start()
try{
Thread.sleep(5500)
}catch(Exception e){
}
/*
如果使用Thread.stop方法停止线程,不能保证这个线程是否完整的运行完成一次
run方法但是如果使用停止的标记位,那么可以保正在真正停止之前完整的运行完
成一次run方法
*/
th.stop()
st.stopThread()
}
}
通过调用interrupt方法可以使得处于阻塞状态的线程抛出一个异常,即interrupt方法可以用来中断一个正处于阻塞状态的线程;另外,改方法还会设置线程的中断状态(注:isInterrupted()可以用来查询中断状态)。
线程阻塞在reader.readLine()时,即使主线程改变了标志变量,但是并不能立即结束子线程,只有等待阻塞被打破,且运行到下一次循环条件判断的时候才能终止。所以在使用这种方法时,应该考虑到阻塞这种情况。当然,如果整个循环内的操作属于同一事务时,这种方法倒很不错。
调用线程对象的interrupt()时,sleep的线程会抛出InterruptedException异常,从而中断循环,终止线程。但是如果是IO如输入这些阻塞,中断的方法又不起作用了,还有就是对于没有阻塞的线程,调用interrupt()是达不到终止线程的效果的。