stopThread 停止线程的方法

做一个标记,当满足某个条件 线程提前被结束 从而提前结束线程

package com.icss.biz.ppt;

/**
 * 结束线程的方法
 * @author sanch
 *
 */
public class StopThreadTest implements Runnable {

	private boolean stopFlag = true;
	@Override
	public void run() {
		int i = 0 ; 
		while(stopFlag) {
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			i++;
			System.out.println(Thread.currentThread().getName()+"----runing i="+i);
		}
		
	}
	public void stopThread() {
		stopFlag = false;
	}
	public static void main(String[] args) {
		int i = 0;
		StopThreadTest stopThreadTest = new StopThreadTest();
		
		new Thread(stopThreadTest).start();
		
		while(true) {
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			i++;
			System.out.println("*******************"+Thread.currentThread().getName()+"-------"+i);
			if(i > 10) {
				stopThreadTest.stopThread();
			}
		}

	}

	

}

猜你喜欢

转载自blog.csdn.net/weixin_39209728/article/details/81540710