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


過期的suspend()、resume()、stop()

不建議使用這三個函數來停止線程,以suspend()方法為例,在調用后,線程不會釋放已經占有的資源(比如鎖),而是占有着資源進入睡眠狀態,這樣容易引起死鎖問題。同樣,stop()方法在終結一個線程是不會保證線程的資源正常釋放,通常識沒有給予線程完成資源釋放工作的機會,因此會導致程序可能工作在不確定的狀態下。

兩種安全終止線程的方法

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();
	
	
}
}

運行結果

兩種方式,一是調用interrupt()方法,其實這也是一種中斷標志的方式;二是自己在線程中自定義一個標志位;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM