No4.线程中断+Thread.sleep()的用法

时间:2021-08-18 22:27:05

与线程中断有关的,有三个方法,这三个方法看起来很像。

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