【Java多线程】——停止线程(3)

之前的文章中提到了Thread中的方法stop()方法,虽然此方法可以用来使线程终止,但是使用此方法是十分暴力的,会造成一些不安全的后果。调用stop()方法后程序会抛出java.lang.ThreadDeath异常,但在通常情况下,此异常不需要显示的捕捉。

在java中stop()方法已经被作废,这是因为如果强制让线程停止,可能会是一些清理工作得不到完成,另外一个情况就是对于锁定的对象进行了解锁,导致数据得不到同步处理,会出现数据不一致的问题。

使用stop释放锁会造成数据不一致的后果,如果出现这种结果,程序处理数据就有可能遭到破坏,最终导致执行流程错误,所以一定要特别注意。

下面来看一个例子,创建类synObject如下:

public class synObject {
	private String username = "a";
	private String password = "aa";
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	synchronized public void init(String username, String password) {
		try {
			this.username = username;
			Thread.sleep(200000);
			this.password = password;
		}
		catch(InterruptedException e) {
			e.printStackTrace();
		}
	}
}

其中username和password初始化为a和aa

Mythread和Run类如下:

public class Mythread extends Thread{
	private synObject object;
	public Mythread(synObject object) {
		super();
		this.object = object;
	}
	@Override
	public void run() {
		object.init("b", "bb");
	}
}
public class Run {
	public static void main(String args[]) throws InterruptedException {
		try {
			synObject object = new synObject();
			Mythread mt = new Mythread(object);
			mt.start();
			Thread.sleep(200);
			mt.stop();
			System.out.println(object.getUsername()+
					" "+object.getPassword());
		}
		catch(InterruptedException e) {
			e.printStackTrace();
		}
	}
}

运行后结果为:

b aa

可以看到在init方法执行的过程中,线程被强制stop(),所以被迫释放了锁,而被操作的对象object出现了数据不一致的结果。显然stop()方法在功能上是有缺陷的,所以不建议使用此方法。

猜你喜欢

转载自blog.csdn.net/u012198209/article/details/80197782