1. 程式人生 > >No4.執行緒中斷+Thread.sleep()的用法

No4.執行緒中斷+Thread.sleep()的用法

與執行緒中斷有關的,有三個方法,這三個方法看起來很像。

public void Thread.interrupt()				//中斷執行緒
public boolean Thread.isInterrupted()			//判斷是否被中斷
public static boolean Thread.interrupted()		//判斷是否被中斷,並清除當前中斷狀態

Thread.sleep()函式的用法:
public class TestThread extends Thread{
	
	public static void main(String[] args) throws InterruptedException {
		Thread t1 = new Thread("xiaoming"){
			@Override
			public void run(){
				while(true){
					System.out.println(Thread.currentThread().getName());
					if(Thread.currentThread().isInterrupted()){
						System.out.println("Interruted!");
						break;
					}
					try {
						Thread.sleep(2000);
					} catch (Exception e) {
						// TODO: handle exception
						System.out.println("Interrupted When Sleep");
						//設定中斷狀態
						Thread.currentThread().interrupt();
					}
					System.out.println("準備掛起");
					Thread.yield();
				}
			}
		};
		t1.start();
		Thread.sleep(3000);
		t1.interrupt();
	}
	
}