package old.interruptThread.model;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;


/**
 * 线程关闭模型1 
 * 宗旨：外部线程通知该线程中断，该线程自行业务结束 
 * 非阻塞的循环业务操作，在循环中使用stop标示来结束业务循环
 * 
 * @date Feb 21, 2013 10:30:53 AM
 * @author ZhangGang
 * 
 */
public class SimpleModel1 implements Runnable {
	volatile boolean stop = false;

	public static void main(String[] args) throws Exception {
//		Thread thread = new Thread(new SimpleModel1(), "My Thread2");
		ExecutorService service = Executors.newFixedThreadPool(1);
		System.out.println("Starting thread...");
		Future<String> future = service.submit(new SimpleModel1(),"");
		Thread.sleep(4000);
		System.out.println("Interrupting thread...");
		future.cancel(true) ; // 中断线程
		Thread.sleep(3000);
		System.out.println("Stopping application...");
		service.shutdownNow();
	}

	public void run() {
		for (int i = 0; i < 10000000l && !stop; i++) {
			/* 模拟睡眠1秒操作 替换为完整的业务 */
			long time = System.currentTimeMillis();
			while ((System.currentTimeMillis() - time < 1000)) {
			}
			
			/**
			 * Thread.currentThread().isInterrupted() 为获取线程中断状态，获取后不改变状态值
			 * ps：catch(InterruptedException e)异常捕获 上面的取值会改变为false
			 */
			System.out.println("My Thread is running... isInterrupted? "+Thread.currentThread().isInterrupted());

			if (Thread.currentThread().isInterrupted()) { // 该值为读取
															// 线程中断状态，不会改变中断状态的值
				System.out.println("结束线程...");
				stop = true;
			}
			else if (Thread.currentThread().isInterrupted()) { // 该值为读取
				System.out.println("结束线程...");
				return;
			}
			
			/**
			 * if 和 else if的区别在于 else if没有"My Thread exiting under request..."的输出
			 * 推荐使用if 判断
			 * */
		}
		System.out.println("My Thread exiting under request...");
	}
}