安全的终止线程的两种方法

###过时的suspend()、resume()、stop() 不建议使用这三个函数来中止线程,以suspend()方法为例,在调用后,线程不会释放已经占有的资源(好比锁),而是占有着资源进入睡眠状态,这样容易引发死锁问题。一样,stop()方法在终结一个线程是不会保证线程的资源正常释放,一般识没有给予线程完成资源释放工做的机会,所以会致使程序可能工做在不肯定的状态下。 ###两种安全终止线程的方法java

package test;

import java.util.concurrent.TimeUnit;

public class ShowDownThread {
private static class TargetRunnable implements Runnable{
	private boolean isCancel = false; //自定义一个终止标志位;
	private long  i;
	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(!isCancel&&!Thread.currentThread().isInterrupted()) {
			i++;
		}
		System.out.println("Count i="+i);
	}
	
	public void cancel() {
		isCancel =true;
	}
	
}
public static void main(String[] args) throws InterruptedException {
	TargetRunnable  runnable = new TargetRunnable();
	Thread thread = new Thread(runnable,"CounThread");
	thread.start();
	TimeUnit.SECONDS.sleep(1);  //底层是调用的 Thread.sleep(ms, ns);
	thread.interrupt();// Just to set the interrupt flag;
	
	TargetRunnable runnable1 = new TargetRunnable();
	Thread thread1 = new Thread(runnable1,"CountThread1");
	thread1.start();
	TimeUnit.SECONDS.sleep(1);
	runnable1.cancel();
	
	
}
}

运行结果 <font color= red>两种方式,一是调用interrupt()方法,其实这也是一种中断标志的方式;二是本身在线程中自定义一个标志位;</font>安全

相关文章
相关标签/搜索