Skip to content

Latest commit

 

History

History
88 lines (68 loc) · 1.86 KB

停止線程.md

File metadata and controls

88 lines (68 loc) · 1.86 KB

停止線程

方式

  • stop 方法 已過時。
  • run 方法結束 任務中都會有循環結構,只要控制住循環就可以結束任務。 控制循環通常用定標記來完成。 但是如果現成處於了凍結狀態,將無法讀取標記。
  1. interrupt(): 將線程從凍結狀態強制恢復到運行狀態中來,讓線程具備 CPU 執行資格。 但是強制動作會發生 InterruptedException,要記得處理。
  • join(): 臨時決定加入一個現成運算時可以使用 join 方法。
  • toString(): 返回該線程的字符串表現形式,包刮線程名稱、優先級和線程組。
  • 暫停當前正在執行的線程對象,並執行其他線程。

Example

public class StopThread implements Runnable {
	
	private boolean flag = true;//定義標記以停止線程
		
	public synchronized void run() {
			
		while(flag) {
				
			try {
					
				wait();
					
			} catch(InterruptedException e) {
					
				System.out.println(Thread.currentThread().getName() + " @ " + e);
				flag = false;
			}
			    System.out.println(Thread.currentThread().getName());
		}
	}
		
	public void setFlag() {
			
		flag = false;
	}
}

public class StopThreadDemo {

	public static void main(String[] args) {
		
		StopThread s = new StopThread();
		
		Thread t1 = new Thread(s);
		Thread t2 = new Thread(s);
		
		t1.start();
		t2.setDaemon(true);//設置為後台線程,依附於前台線程,前台線程結束,後台線程也跟著結束
		t2.start();
		
		int num = 1;
		for(;;) {//無限循環
			
			if(++num == 10) {
				
//				s.setFlag();
				t1.interrupt();
//				t2.interrupt();
				break;
			}
			System.out.println("main = " + num);
		}
		System.out.println("The End");
	}
}

打印結果

main = 2
main = 3
main = 4
main = 5
main = 6
main = 7
main = 8
main = 9
The End
Thread-0 @ java.lang.InterruptedException
Thread-0