Java学习 - Thread的Stop方法以及替换实现

在Android中新线程如果不及时停止是很麻烦的,我们这一般用线程池来完成,但是有些时候不能依赖线程池。这里Stop方法不推荐使用,我给个具体的例子:

public class DeprecatedStop extends Object implements Runnable {
	public void run() {
		int count = 0;
		while (count < 20) {
			System.out.println("Running ... count=" + count);
			count++;
			try {
				Thread.sleep(300);
			} catch (InterruptedException x) {
				// ignores
			}
		}

		// the code maybe not executed
		System.out.println("stoped");
	}

	public static void main(String[] args) {
		DeprecatedStop ds = new DeprecatedStop();
		Thread t = new Thread(ds);
		t.start();
		try {
			Thread.sleep(2000);
		} catch (InterruptedException x) {
			// ignore
		}
		// Abruptly stop the other thread in its tracks!
		t.stop();
	}
}

可能的运行结果:

Running ... count=0
Running ... count=1
Running ... count=2
Running ... count=3
Running ... count=4
Running ... count=5
Running ... count=6

可以发现程序中的打印stoped并没有执行,所以说如果在程序中有其他操作,如果线程突然stop是会带来严重的影响的。所以怎么也应该使用该操作。当然如果是我上面的程序代码突然stop的影响其实是没有的,但是如果是其他打开文件最后需要释放或者什么的就会带来严重的影响了。

如何在程序中对其进行停止呢?

public class AlternateStop extends Object implements Runnable {
	private volatile boolean stopRequested;
	private Thread runThread;

	public void run() {
		runThread = Thread.currentThread();
		stopRequested = false;
		int count = 0;
		while (!stopRequested) {
			System.out.println("Running ... count=" + count);
			count++;
			try {
				Thread.sleep(300);
			} catch (InterruptedException x) {
				Thread.currentThread().interrupt(); // re-assert interrupt
			}
		}

		System.out.println("stoped");
	}

	public void stopRequest() {
		stopRequested = true;
		if (runThread != null) {
			runThread.interrupt();
		}
	}

	public static void main(String[] args) {
		AlternateStop as = new AlternateStop();
		Thread t = new Thread(as);
		t.start();
		try {
			Thread.sleep(2000);
		} catch (InterruptedException x) {
			// ignore
		}
		as.stopRequest();
	}
}

可能的运行结果如下:

Running ... count=0
Running ... count=1
Running ... count=2
Running ... count=3
Running ... count=4
Running ... count=5
Running ... count=6
stoped

这样我们就解决了强制stop的问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值