JAVA并发实现三(线程的挂起和恢复)

package com.subject01;
/**
 * 通过标识位,实现线程的挂起和回复
 * com.subject01.AlternateSuspendResume.java
 * @author 孙涛
 * 2016年5月9日
 */
public class AlternateSuspendResume implements Runnable {

	private volatile int firstVal ;
	private volatile int secondVal ;
	// 线程挂起的标识
	private volatile boolean suspendFlag ;

	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			suspendFlag = false ;
			firstVal = 0 ;
			secondVal = 0 ;
			workMethod();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	private boolean areValueEqual(){
		return firstVal == secondVal ;
	}

	private void workMethod() throws InterruptedException{
		int val = 1 ;
		while(true){
			// 仅当线程挂起的时候,才运行这段代码
			waitWhileSuspended();

			stepOne(val);
			stepTwo(val);
			val++ ;

			// 仅当线程挂起的时候才运行这段代码
			waitWhileSuspended();
			
			Thread.sleep(200);
		}
	}

	private void stepTwo(int val) {
		secondVal = val ;
	}

	private void stepOne(int val) throws InterruptedException {
		firstVal = val ;
		Thread.sleep(300);
	}

	private void waitWhileSuspended() throws InterruptedException {
		//这是一个“繁忙等待”技术的示例。  
		//它是非等待条件改变的最佳途径,因为它会不断请求处理器周期地执行检查,
		while(suspendFlag){
			Thread.sleep(200);
		}
	}

	private void supendRequest() {
		this.suspendFlag = true ;
	}
	
	private void resumeRequest() {
		this.suspendFlag = false ;
	}
	
	public static void main(String[] args) {
		AlternateSuspendResume asr = new AlternateSuspendResume();
		Thread t = new Thread(asr);
		t.start();
		try {
			Thread.sleep(2000);
		} catch (Exception e) {
		}

		for (int i = 0; i < 10; i++) {
			asr.supendRequest();
			//让线程有机会注意到挂起请求  
			//注意:这里休眠时间一定要大于  
			//stepOne操作对firstVal赋值后的休眠时间,即300ms,  
			//目的是为了防止在执行asr.areValuesEqual()进行比较时,  
			//恰逢stepOne操作执行完,而stepTwo操作还没执行  
			try { Thread.sleep(350); }   
			catch ( InterruptedException x ) { }  

			System.out.println("dsr.areValuesEqual()=" +   
					asr.areValueEqual());  

			asr.resumeRequest();  

			try {   
				//线程随机休眠0~2秒  
				Thread.sleep(  
						( long ) (Math.random() * 2000.0) );  
			} catch ( InterruptedException x ) {  
				//略  
			}  
		}  

		System.exit(0); //退出应用程序  
	}
}

 |--通过标识位合理的控制线程挂起的位置; 

   |--线程终止:线程在执行完run()方法之后,或者在run()中使用return,都可以将线程进行终止;同时也可以通过标识位灵活的控制线程终止的位置;

   参考地址:http://blog.csdn.net/ns_code/article/details/17095733

原文地址:https://www.cnblogs.com/xiaotao726/p/5475785.html