java線程(暫停、恢復、結束)前引


一、suspend、resume、stop  (過期的暫停、恢復、結束)

線程得益於它的run方法,在其中不斷地循環來達到預期的目的,而很多時候,經常需要對這略過機械化的“小東西 ”進行一些控制。

在線程Thread方法中,原先存在着很方便、很人性化的控制,讓其可以乖乖 暫停、恢復、結束,不過是一句話的事而已。

如下:

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class TEST1 {

	public static void main(String[] args) throws InterruptedException {
		DateFormat format=new SimpleDateFormat("HH:mm:ss");
		Thread printThread=new Thread(new Runner(),"printThread");
		printThread.start();
		TimeUnit.SECONDS.sleep(3);//main暫停3秒
		System.out.println("main suspend the printfThread at "+format.format(new Date()));
		printThread.suspend();//線程暫停
		TimeUnit.SECONDS.sleep(3);//main暫停3秒
		System.out.println("main resume the printfThread at "+format.format(new Date()));
		printThread.resume();
		TimeUnit.SECONDS.sleep(3);//main暫停3秒
		System.out.println("main stop the printfThread at "+format.format(new Date()));
		printThread.stop();
		TimeUnit.SECONDS.sleep(3);//main暫停3秒 此時printThread 已經停止 以下不會再有輸出
	}
	static	class Runner implements Runnable{
		@Override
		public void run() {
			DateFormat format=new SimpleDateFormat("HH:mm:ss");
			while(true){
				System.out.println(Thread.currentThread().getName()+" Run at"+format.format(new Date()));
				try {
					Thread.sleep(1000);//睡眠1秒
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
<strong><span style="color:#ff0000;">輸出結果:</span></strong><pre name="code" class="java">printThread Run at13:54:22
printThread Run at13:54:23
printThread Run at13:54:24
main suspend the printfThread at 13:54:25
main resume the printfThread at 13:54:28
printThread Run at13:54:28
printThread Run at13:54:29
printThread Run at13:54:30
main stop the printfThread at 13:54:31
</pre>


然而,suspend、resume、stop 具有一定的副作用,或者說它處理的不夠好,雖然表面上它是達到了意圖,但suspend()方法在調用暫停之後,該線程並不會去釋放已經佔有的資源(比如你使用了鎖對象,用其進行一些同步操作,而suspend將此線程暫停之後卻沒有釋放鎖,導致其他線程無法獲得對象,將會繼續排隊等待,一旦這樣的操作多了,那麼這就是另一種死鎖的體現。suspend、resume、stop等方法並不能很好地解決線程的控制問題,反而還會造成不可預料的影響。因此,被捨棄使用。

暫停與恢復 一般以等待/通知 機制來實現。 條件循環 處理邏輯等。

結束線程以打破循環條件爲主。

例:

import java.sql.Time;
import java.util.concurrent.TimeUnit;

public class Test {
public static void main(String[] args) {
	myThread one =new myThread(1);
	Thread aa=new Thread(one);
	aa.start();
	myThread two =new myThread(2);
	Thread aaa=new Thread(two);
	aaa.start();
	try {
		TimeUnit.SECONDS.sleep(3);
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
	//aa.interrupt();
	one.exit();
}
}

class myThread implements Runnable{
	private volatile boolean flag=true;
 private int i,k;
  public myThread(int k) {
	this.k=k;
}
	@Override
	public void run() {
	while(this.flag&&!Thread.currentThread().isInterrupted()){
		i++;
	}
		System.out.println(k+"Thread is stop and i="+i);
	}
	public void exit(){
		this.flag=false;
	} 
}

輸出結果:  1Thread is stop and i=1567966856     運用interrupt 和exit 修改while 條件 均可達到結束效果。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章