Thread 重要方法总结
1.isAlive()
线程已经调用了start方法且没有结束
返回true时,线程对应于Runnable,Waiting,Timed_Waiting,Blocked四种State,不要以为 只是对应于Runnable状态
返回false时,线程对应于New,Terminated两种状态
2.isInterrupted()
线程是否interrupted status 是否为true,注意interrupted为true只是表明该线程的interrupt方法被调用了,该方法只是把interrupted状态设为true,建议线程终止,并不具有强制结束线程的功能,线程结束与否要看线程的run中对该状态为true时如何响应.如下的代码演示了线程当该状态变为true时退出运行.当然,线程可以忽略该状态.所以依靠interrupt方法来终止线程是不可行的.
当处于interrupted状态的线程调用sleep,join,wait方法时会抛出 InterruptedException 异常,而且该状态会被重置为false
//被interrupt后终止线程
import java.util.Random;public class TestThreadStatus {/** * @param args */public static void main(String[] args) {Thread t = new TestThread(); try {t.start(); try {while(true){try {Thread.sleep(5000);t.interrupt();} catch (InterruptedException e) {e.printStackTrace();}}} catch (Exception e) {e.printStackTrace();}} catch (Exception e) {e.printStackTrace();}}}class TestThread extends Thread {public void run() {try {while (true) {try {// 为true,所以下列三个方法的调用(当thread已经被interrupt或者稍后被interrupt)都会抛出//InterruptedException System.err.println("Thread is interrupted = "+this.isInterrupted()); int random = (int)(new Random().nextDouble()*3); //当线程调3个方法任意一个都会导致异常,并清空interrupted if(random == 0){ System.err.println("Interrupt a thread blocked by wait()"); synchronized("lock"){ "lock".wait(); //说明wait除了被notify之外,还有可能被interrupt释放 } } else if(random == 1){ System.err.println("Interrupt a thread blocked by sleep()"); Thread.sleep(20000); } else { System.err.println("Interrupt a thread blocked by join()"); Thread tt = new OneThread(); tt.start();//一定要启动,下一行的join才会阻塞 tt.join();//等待线程tt die,如果tt线程状态为new或者terminated(alive=false),都会马上返回 } } catch (InterruptedException e) {e.printStackTrace();System.err.println("Thread is interrupted = "+this.isInterrupted());// 为false,因为已经被清空}}} catch (Exception e) {e.printStackTrace();}}}class OneThread extends Thread {public void run() {try {while (true) {try {Thread.sleep(5000);} catch (Exception e) {e.printStackTrace();}}} catch (Exception e) {e.printStackTrace();}}}