Java多线程3--停止线程

关于线程的停止,主要有两种,一种是自然停止,即线程体正常执行完毕。还有一种则是外部干涉,我们主要讲的是外部干涉。其实也比较简单

外部干涉:

1)线程类中定义线程体使用的标识,如boolean型

2)线程体中使用该标识

3)提供对外的方法改变该标识

4)外部根据条件调用该标识

我们还是用例子来进行说明,首先创建一个Study类

public class Study implements Runnable {
	//线程类中定义线程体使用的标识
	private boolean flag = true;
	int count = 0;
	//重写run方法
	public void run(){
		//线程体使用该标识
		while(flag){
			System.out.println("study thread...."+count++);
		}
	}
	//对外提供方法改变标识
	public void stop(){
		this.flag=false;
	}

}

然后创建一个测试类 Demo01

public class Demo01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Study s=new Study();
		new Thread(s).start();
		//外部干涉
		for (int i=0;i<1000;i++){
			if(i==500){
				s.stop();
				//停止时不一定是500,由于CPU运行太快故不是非常准确
			}
			System.out.println("main-->"+i);
		}
	}
}

注:此stop非彼stop,这里的stop 是我们自定义的方法,Thread里也有一个stop方法,但是并不推荐用于停止线程

猜你喜欢

转载自blog.csdn.net/qq_36986067/article/details/81276693