1.用标识符flag来停止。
public void run() { // TODO Auto-generated method stub while (flag) { System.out .println(name + ":" + (++num)); if(num==10000) changeFlag(); //Thread.currentThread().interrupt(); } } public void changeFlag() { flag=false; }或者:
public void changeFlag() { flag=false; } public void run() { // TODO Auto-generated method stub while (flag) { System.out .println(name + ":" + (++num)); } } public static void main(String[] args) { SimpleThreadDemo simpleThreadDemo1 = new SimpleThreadDemo("Sting "); Thread t1 = new Thread(simpleThreadDemo1); t1.start(); int i=0; while(true) { if(++i==100000) { simpleThreadDemo1.changeFlag(); break; } } }
2.用interrupt()方法来停止,但是得用(!Thread.interrupted())判断一下方可以终止线程,起到了flag的作用
public void run() { // TODO Auto-generated method stub while (!Thread.interrupted()) { System.out .println(name + ":" + (++num)); if(num==10000) Thread.currentThread().interrupt(); } }或者:
public void run() { // TODO Auto-generated method stub while (!Thread.interrupted()) { System.out .println(name + ":" + (++num)); } } public static void main(String[] args) { SimpleThreadDemo simpleThreadDemo1 = new SimpleThreadDemo("Sting "); Thread t1 = new Thread(simpleThreadDemo1); t1.start(); int i=0; while(true) { if(++i==100000) { t1.interrupt(); break; } } }
3.也可以用stop()方法终止线程,但是该方法已经被废弃,虽然可以,但已经不推荐用了。对于冻结的线程仅凭flag标识是不足以终止线程的,主线程结束了,t2 t1直接wait()了,如果线程处于了冻结状态,就无法读取标记,所以就引入了第二种结束线程的方式interrupt(),直接用interrupt()方法终止线程是无效的,但是interrupt()方法可以处理那种将线程从冻结状态强制恢复到运行状态中,使线程回到具备CPU执行资格的状态,但是会发生中断异常(InterruptException)
class StopThread implements Runnable { private boolean flag = true; public synchronized void run() { while(flag) { try { wait(); } catch (InterruptedException e) { // TODO: handle exception System.out.println(Thread.currentThread().getName()+"........."+e); flag = false;//注意处理,不加这个会导致线程继续等待,主线程结束t1 t2未结束 } System.out.println(Thread.currentThread().getName()+"-++--"); } } public void ChangeFlag() { flag = false; } } public class Main { public static void main(String[] args) { StopThread s = new StopThread(); Thread t1 = new Thread(s); Thread t2 = new Thread(s); t1.start(); t2.start(); int i = 0; while(true) { if(++i == 20)//i达到20后结束所有线程 { //s.ChangeFlag(); t1.interrupt(); t2.interrupt(); break; } System.out.println("Main.main"+i); } System.out.println("Final"); } }
原文地址:http://blog.csdn.net/mnmlist/article/details/45849875