Java线程的状态
Thread.State类定义了以下6种线程状态
- 新建状态(NEW):未启动的线程处于该状态,即未调用该线程的start()方法时。
- 可运行态(RUNNABLE):正在Java虚拟机中执行的线程处于该状态。
- 阻塞状态(BLOCKED):正在等待一个监视器锁的被阻塞线程处于该状态。
- 无限期等待状态(WAITING):处于该状态的线程,无限期等待另一个线程执行特定操作唤醒当前线程。
- 限期等待状态(TIMED_WAITING):处于该状态的线程,在指定的等待时间内等待另一线程执行特定操作唤醒当前线程,当等待时间结束后,会自动从无限期等待状态变为可运行态。
- 终止状态(TERMINATED):已结束的线程处于此状态。
可调用Thread类的getState()获取线程的状态。
静态方法
Sleep(long millis)
使当前执行的线程睡眠(即暂时停止执行)参数制定的毫秒数。
实例方法
isAlive()
测试当前线程是否存活。
Join()
一个线程调用另外一个线程的join方法,使调用线程进入无限期等待,直到被调用线程结束。
join(long millis)
一个线程调用另一个线程的join(long millis)方法,使调用线程进入限期等待,直到被调用线程结束或者超过等待时间限制。源码如下
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;
}
}
}
interrupt()
- 在调用Thread.sleep(),Thread.join() 或 Object.wait()等方法使一个线程处于可中断的等待的状态时,如果另一个线程调用interrupt 函数,则会抛出InterruptedException,同时该线程会立即结束等待状态并清除中断标记,进入异常处理块。
- 在一个线程中调用另一个线程的interrupt()方法,会向被调用线程发出信号:线程中断状态已被设置,该方法仅仅设置中断标记,并不中断被调用线程。
isInterrupted()
用来判断当前线程的中断状态,该函数不影响中断标记。
interrupted()
静态方法,判断调用线程的中断状态,并且会清除中断标记。接下来看一个代码的例子。
public class InterruptTest extends Thread{
@Override
public void run() {
for (int i = 0; i < 100000; i++){
}
System.out.println(isInterrupted());
System.out.println(isInterrupted());
System.out.println(interrupted());
System.out.println(interrupted());
}
public static void main(String[] args) {
Thread t = new InterruptTest();
t.start();
t.interrupt();
}
}
上面的代码在主线程中调用了 interrupt 函数设置线程Thread-0的中断标志,在Thread-0的run()方法中先调用2次 isInterrupted 函数,两次的结果都是 true,表示发生了中断,但该函数不恢复中断。随后调用两次 interrupted,第一次结果为 true,第二次结果为 false,这说明 interrupted 函数不仅判断是否发生中断,而且会清除中断标志,使当前线程从中断状态中恢复。
下面的代码说明了interrpt使被中断线程立即结束等待状态
public class InterruptTest extends Thread{
@Override
public void run() {
try {
sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("线程" + this.getName() + "被中断");
System.out.println("中断标记:" + String.valueOf(interrupted()));
e.printStackTrace();
}
}
public static void main(String[] args) {
Thread t = new InterruptTest();
t.start();
t.interrupt();
}
}
执行上面的代码,Thread-0线程在调用sleep函数进入等待状态后被中断,立即从等待状态中恢复,并执行异常处理的代码。