安全的終止線程的兩種方法

###過時的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>安全

相關文章
相關標籤/搜索