Java多线程编程学习笔记之二:线程挂起、恢复与终止的正确方法(含代码)(一)

2014-11-24 08:14:30 · 作者: · 浏览: 2

挂起和恢复线程

Thread 的API中包含两个被淘汰的方法,它们用于临时挂起和重启某个线程,这些方法已经被淘汰,因为它们是不安全的,不稳定的。如果在不合适的时候挂起线程(比如,锁定共享资源时),此时便可能会发生死锁条件——其他线程在等待该线程释放锁,但该线程却被挂起了,便会发生死锁。另外,在长时间计算期间挂起线程也可能导致问题。

下面的代码演示了通过休眠来延缓运行,模拟长时间运行的情况,使线程更可能在不适当的时候被挂起:

public class DeprecatedSuspendResume extends Object implements Runnable{

	//volatile关键字,表示该变量可能在被一个线程使用的同时,被另一个线程修改
	private volatile int firstVal;
	private volatile int secondVal;

	//判断二者是否相等
	public boolean areva luesEqual(){
		return ( firstVal == secondVal);
	}

	public void run() {
		try{
			firstVal = 0;
			secondVal = 0;
			workMethod();
		}catch(InterruptedException x){
			System.out.println(interrupted while in workMethod());
		}
	}

	private void workMethod() throws InterruptedException {
		int val = 1;
		while (true){
			stepOne(val);
			stepTwo(val);
			val++;
			Thread.sleep(200);  //再次循环钱休眠200毫秒
		}
	}
	
	//赋值后,休眠300毫秒,从而使线程有机会在stepOne操作和stepTwo操作之间被挂起
	private void stepOne(int newVal) throws InterruptedException{
		firstVal = newVal;
		Thread.sleep(300);  //模拟长时间运行的情况
	}

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

	public static void main(String[] args){
		DeprecatedSuspendResume dsr = new DeprecatedSuspendResume();
		Thread t = new Thread(dsr);
		t.start();

		//休眠1秒,让其他线程有机会获得执行
		try {
			Thread.sleep(1000);} 
		catch(InterruptedException x){}
		for (int i = 0; i < 10; i++){
			//挂起线程
			t.suspend();
			System.out.println(dsr.areva luesEqual()= + dsr.areva luesEqual());
			//恢复线程
			t.resume();
			try{ 
				//线程随机休眠0~2秒
				Thread.sleep((long)(Math.random()*2000.0));
			}catch(InterruptedException x){
				//略
			}
		}
		System.exit(0); //中断应用程序
	}
}
某次运行结果如下:

\

从areva luesEqual()返回的值有时为true,有时为false。以上代码中,在设置firstVal之后,但在设置secondVal之前,挂起新线程会产生麻烦,此时输出的结果会为false(情况1),这段时间不适宜挂起线程,但因为线程不能控制何时调用它的suspend方法,所以这种情况是不可避免的。

当然,即使线程不被挂起(注释掉挂起和恢复线程的两行代码),如果在main线程中执行asr.areva luesEqual()进行比较时,恰逢stepOne操作执行完,而stepTwo操作还没执行,那么得到的结果同样可能是false(情况2)。


下面我们给出不用上述两个方法来实现线程挂起和恢复的策略——设置标志位。通过该方法实现线程的挂起和恢复有一个很好的地方,就是可以在线程的指定位置实现线程的挂起和恢复,而不用担心其不确定性。

对于上述代码的改进代码如下:

public class AlternateSuspendResume extends Object implements Runnable {

	private volatile int firstVal;
	private volatile int secondVal;
	//增加标志位,用来实现线程的挂起和恢复
	private volatile boolean suspended;

	public boolean areva luesEqual() {
		return ( firstVal == secondVal );
	}

	public void run() {
		try {
			suspended = false;
			firstVal = 0;
			secondVal = 0;
			workMethod();
		} catch ( InterruptedException x ) {
			System.out.println(interrupted while in workMethod());
		}
	}

	private void workMethod() throws InterruptedException {
		int val = 1;

		while ( true ) {
			//仅当贤臣挂起时,才运行这行代码
			waitWhileSuspended(); 

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

			//仅当线程挂起时,才运行这行代码
			waitWhileSuspended(); 

			Thread.sleep(200);  
		}
	}

	private void stepOne(int newVal) 
					throws InterruptedException {

		firstVal = newVal;
		Thread.sleep(300);  
	}

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

	public void suspendRequest() {
		suspended = true;
	}

	public void resumeRequest() {
		suspended = false;
	}

	private void waitWhileSuspended() 
				throws InterruptedException {

		//这是一个“繁忙等待”技术的示例。
		//它是非等待条件改变的最佳途径,因为它会不断请求处理器周期地执行检查, 
		//更佳的技术是:使用Java的内置“通知-等待”机制
		while ( suspended ) {
			Thread.sleep(200);
		}
	}

	public static void main(String[] args) {
		AlternateSuspendResume asr = 
				new AlternateSuspendResume();

		Thread t = new Thread(asr);
		t.start();

		//休眠1秒,让其他线程有机会获得执行
		try { Thread