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

来源:互联网 发布:边伯贤2017知乎 编辑:程序博客网 时间:2024/04/29 13:52

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

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"){@Overridepublic 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 exceptionSystem.out.println("Interrupted When Sleep");//设置中断状态Thread.currentThread().interrupt();}System.out.println("准备挂起");Thread.yield();}}};t1.start();Thread.sleep(3000);t1.interrupt();}}



0 0