线程的状态
interrupted静态方法:测试当前线程(current thread)是否是中断状态,执行后将状态标识清除,置为false。
isInterrupted实例方法: 测试线程Thread对象(this thread)是否是中断状态,不会清除标识状态。
-
BLOCKED 阻塞
Thread state for a thread blocked waiting for a monitor lock. -
NEW 新建
Thread state for a thread which has not yet started. -
RUNNABLE 运行或就绪
Thread state for a runnable thread. -
TERMINATED 终止
Thread state for a terminated thread. -
TIMED_WAITING 有限等待
Thread state for a waiting thread with a specified waiting time. -
WAITING 无限等待
Thread state for a waiting thread.
public class TestThread {public static void main(String[] args) throws InterruptedException {
MyThread thread1 = new MyThread();
thread1.setName(“thread1”);
System.out.println(“thread1状态为:” + thread1.getState());
thread1.start();
System.out.println(“thread1状态为:” + thread1.getState());
Thread.sleep(1000);
System.out.println(“thread1状态为:” + thread1.getState());
}
}
class MyThread extends Thread {
public MyThread() {
System.out.println("进入MyThread构造方法的线程为:" + Thread.currentThread().getName());
}
@Override
public void run() {
System.out.println("当前线程为:" + Thread.currentThread().getName() + " 线程的状态为:"
+ Thread.currentThread().getState());
}
}
多线程
可以把线程归到某一个线程组,线程组中可以有线程对象,也可以有线程组,这样的结构类似于树的形式。
执行main方法的线程名为:main,它所属线程组的组名也为:main。
线程或线程组会自动归属到当前线程组中。
当线程组调用interrupt方法时,这个线程组中的线程都会停止。
线程的异常
可以把线程归到某一个线程组,线程组中可以有线程对象,也可以有线程组,这样的结构类似于树的形式。
执行main方法的线程名为:main,它所属线程组的组名也为:main。
线程或线程组会自动归属到当前线程组中。
当线程组调用interrupt方法时,这个线程组中的线程都会停止。