码迷,mamicode.com
首页 > 编程语言 > 详细

终止线程的方法

时间:2015-05-19 22:43:40      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:线程   flag   interrupt   

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");
	}
}



终止线程的方法

标签:线程   flag   interrupt   

原文地址:http://blog.csdn.net/mnmlist/article/details/45849875

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!