一个线程可以处以一下四种状态之一
①新建(new):当线程被创建时,它只会短暂的处以这一状态,此时,它已经被分配了必须得系统资源,并执行了初始化。此刻线程已经有资格获得CPU时间了,之后调度器 会把这个线程转变为可运行状态或阻塞状态。
②就绪(runnable):此种状态下,只要调度器把时间片分配给线程,线程就可以运行。
③阻塞(blocked):线程能够运行,但有某个条件阻止它的运行。当线程处于阻塞状态时,调度器将忽略线程,不会分配给线程任何CPU时间,直到线程重新回到就绪状态。
④死亡(dead):处于死亡或终止状态的线程将不再是可调度的,并且再也不会获得CPU时间。它的任务已经结束,或不再是可运行的。
进入阻塞状态的情况可能有一下几种
①调用sleep(milliseconds)使任务进入休眠状态,在这种情况下,任务在指定时间内不会运行。
②调用wait()使线程挂起。直到线程得到了notify或notifyAll消息(或者signal或signalAll消息),线程才会进入就绪状态。
③任务等待某个输入/输出完成。
④任务试图在某个对象上调用其同步控制方法,但是对象锁不可用,因为另一个任务已经获得了这个锁。
中断线程
package concurrency;
import java.util.concurrent.*;
import java.io.*;
class SleepBlocked implements Runnable {
public void run() {
try {
TimeUnit.SECONDS.sleep(100);
} catch (InterruptedException e) {
System.out.println("InterruptedException");
}
System.out.println("Exiting SleepBlocked.run()");
}
}
class IOBlocked implements Runnable {
private InputStream in;
public IOBlocked(InputStream is) {
in = is;
}
public void run() {
try {
System.out.println("Waiting for read():");
in.read();
} catch (IOException e) {
if (Thread.currentThread().isInterrupted()) {
System.out.println("Interrupted from blocked I/O");
} else {
throw new RuntimeException(e);
}
}
System.out.println("Exiting IOBlocked.run()");
}
}
class SynchronizedBlocked implements Runnable {
public synchronized void f() {
while (true)
// Never releases lock
Thread.yield();
}
public SynchronizedBlocked() {
new Thread() {
public void run() {
f(); // Lock acquired by this thread
}
}.start();
}
public void run() {
System.out.println("Trying to call f()");
f();
System.out.println("Exiting SynchronizedBlocked.run()");
}
}
public class Interrupting {
private static ExecutorService exec = Executors.newCachedThreadPool();
static void test(Runnable r) throws InterruptedException {
//通过调用submit就可以持有该任务的上下文,返回一个泛型Future<?>,其中有一个未修饰的参数
Future<?> f = exec.submit(r);
TimeUnit.MILLISECONDS.sleep(100);
System.out.println("Interrupting " + r.getClass().getName());
//通过Future<?>可以获得在其上调用cancel方法,可以用它来中断某个特定任务。
f.cancel(true); // Interrupts if running
System.out.println("Interrupt sent to " + r.getClass().getName());
}
public static void main(String[] args) throws Exception {
test(new SleepBlocked());
test(new IOBlocked(System.in));
test(new SynchronizedBlocked());
TimeUnit.SECONDS.sleep(3);
System.out.println("Aborting with System.exit(0)");
System.exit(0); // ... since last 2 interrupts failed
}
}
详见 java编程思想 21.4节