涉及源码的解读暂不在该文章中探究。
1. public static native Thread currentThread():返回该代码段正在被哪个线程调用的信息
2. public final native boolean isAlive():测试线程是否处于活动状态(正在运行或准备运行的状态)
3. 判断线程是否是停止状态 ****
/**
* Tests whether the current thread has been interrupted. The
* <i>interrupted status</i> of the thread is cleared by this method. In
* other words, if this method were to be called twice in succession, the
* second call would return false (unless the current thread were
* interrupted again, after the first call had cleared its interrupted
* status and before the second call had examined it).
*/
public static boolean interrupted() {
return currentThread().isInterrupted(true);
}
测试 当前线程 是否已中断。线程的中断状态会被该方法清除,换句话说,如果该方法被连续调用两次,则第二次调用会返回false(在第一次调用已清除了其中断状态之后,且第二次调用检验完中断状态前,当前线程再次中断的情况除外)
/**
* Tests whether this thread has been interrupted. The <i>interrupted
* status</i> of the thread is unaffected by this method.
*/
public boolean isInterrupted() {
return isInterrupted(false);
}
测试 线程对象(调用者) 是否已中断。注意,该方法不清除中断状态。
/**
* Tests if some Thread has been interrupted. The interrupted state
* is reset or not based on the value of ClearInterrupted that is
* passed.
*/
private native boolean isInterrupted(boolean ClearInterrupted);
测试某个线程是否被中断。中断状态是否重置取决于ClearInterrupted的值。
4. 中断线程(可参考java中断机制)
public void interrupt() 中断线程,但不会停止线程,只是会给指定线程加上一个中断标记。(注意:假如线程在sleep状态下被中断,抛出中断异常且会清除停止状态值,isInterrupted()返回false,反之,在中断状态下调用sleep方法也会抛出中断异常,所以尽量不要这么做)
在sleee状态下调用interrupt方法会抛异常,在interrupt状态下调用sleep方法也会抛异常
5. 停止线程 ******
java中有三种停止线程的方法:
- 使用退出标志正常退出,即run方法完成后线程终止
- 使用stop方法(弃用方法,不再讨论)
- 抛异常中断。
但是真正的难点在于何时手动中断线程。某个线程A负责执行某个任务,它可能并不知道自己何时该停止,可能需要某个条件来确定,而该条件又受其他线程影响,具体的实际情况可能更复杂(不太好表述)。通常做法有两种:
- 创建一个多线程间可视化的volatile变量作为条件标记,当条件满足时,A线程能够通过该标记知道自己该停止了。
- 将线程A的状态置为中断状态(如果能获取线程A的实例对象的话),A线程通过判断自身状态来知道自己是否该停止了。
6. sleep线程休眠
public static native void sleep(long millis) 使当前正在执行的线程休眠指定的毫秒数(不会释放锁)
7. wait线程等待
public final void wait() throws InterruptedException 线程进入等待状态直到被其他线程唤醒,只能在同步块中被调用(会释放锁)
public final native void wait(long timeout) throws InterruptedException 线程等待,除非中途被唤醒,否则指定时间后停止等待,进入就绪状态
8. yield线程退让
public static native void yield(); 当前线程放弃当前已获得的CPU资源,将它让给其他任务去占用CPU执行时间,但是放弃的时间不确定,因为当前线程也会重新加入争抢CPU资源的预执行队列,所以可能刚放弃又马上获得CPU时间片。优先级越高,获得CPU时间片的概率越大(即使优先级最高也不一定必然获得,所谓的优先级执行,是在大量执行次数中才能体现出来的)
9. join线程加入
public final void join() throws InterruptedException {
join(0);
}
public final synchronized void join(long millis)
throws InterruptedException {
long base = System.currentTimeMillis();
long now = 0;
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (millis == 0) {
while (isAlive()) {
wait(0);
}
} else {
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}
方法join()的作用是使所属的线程对象x正常执行run方法中的任务,而使当前线程z无限期的阻塞,直到x线程
销毁后再继续执行线程z后面部分的代码。join(long millis)使当前线程z阻塞指定时间,但是注意,因其地
层调用的是wait(long millis)方法,根据wait方法的特性,指定时间唤醒后并不一定能马上获得CPU资源,
所以只会等待时间更长。
同时,因为底层是wait方法,所以它也会释放锁。