线程常用方法isInterrupted() VS interrupted()和Sleep() VS Suspend()

来源:互联网 发布:js position fixed 编辑:程序博客网 时间:2024/06/04 19:26

isInterrupted() VS interrupted()

1、源码解析

1)interrupted() 测试当前线程是否被中断,是返回true,否返回false

public static boolean interrupted() {        return currentThread().isInterrupted(true);    }

2)isInterrupted()测试该线程是否被中断,是返回true,否返回false
 public boolean isInterrupted() {        return isInterrupted(false);    }
private native boolean isInterrupted(boolean ClearInterrupted);
2、区别

这两种方法都可以在Thread类中判断线程是否通过interrupt方法终止

区别是:

1)interrupted是静态的方法,可以直接通过类名调用;isInterrupted是非静态的,需要通过实例对象来调用。

2)interrupted是用来判断当前线程是否被中断。isInterrupted可以用来判断其他线程是否被中断

Sleep() VS Suspend()

1、源码解析
1)sleep()使当前运行的线程暂时的停止,从运行状态到阻塞,millis之后,进入runnable状态,等待JVM的线程调度。
 public static native void sleep(long millis) throws InterruptedException;
注意:
1、sleep方法有两个重载形式,其中一种不仅仅可以设毫秒还可以设纳秒,但大多数OS平台上的JAVA虚拟机无法精确到毫秒,因此JVM取最接近这个值的毫秒
2、使用sleep方法时必须使用throws或try{...}catch{...}。因为run方法无法使用throws

2)suspend()首先它不建议使用了。它主要是在一个线程中通过suspend方法来挂起另一个线程。通过resume来唤醒。
@Deprecated    public final void suspend() {        checkAccess();        suspend0();    }


参考资料:http://developer.51cto.com/art/200911/162925.htm

0 0
原创粉丝点击