Java线程状态及结束线程的方法

根据 java.lang.Thread.State 中的描述Thread有处于以下6种状态中的一种:

NEW:A thread that has not yet started is in this state

RUNNABLE:A thread executing in the Java virtual machine is in this state

BLOCKED:A thread that is blocked waiting for a monitor lock is in this state

WAITING:A thread that is waiting indefinitely for another thread to perform a particular action is in this state

TIMED_WAITING:A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state

TERMINATED:A thread that has exited is in this state

A thread can be in only one state at a given point in time. These states are virtual machine states which do not reflect any operating system thread states.

状态一  NEW(初始状态)

实现Runnable接口或者继承Thread类可以得到一个线程类,new一个实例出来,就得到了一个处于初始状态的线程。

状态二  RUNNABLE(就绪状态)

调用线程的start(),此线程就进入了就绪状态

就绪状态只说明该线程具有运行的资格,但是调度程序没有挑选到你,你就永远处于就绪状态

当前线程sleep()方法结束,其他线程join()方法结束,等待用户输入完毕,某个线程拿到对象锁,都会让线程进入就绪状态

当前线程时间片用完了,调用当前线程的yield()方法,当前线程进入就绪状态

锁池里的线程拿到对象锁之后,进入就绪状态

线程调度程序从可运行池中选择一个线程作为当前线程时,线程状态会变为运行中状态,这是线程进入运行状态的唯一方式

状态三  BLOCKED(阻塞状态)

该状态是线程阻塞在进入synchronized关键字修饰的方法或者代码块时的状态。

状态四  WAITING(等待)

处于这种状态的线程不会被分配CPU执行时间,且要等待被显式的唤醒,否则线程会无限期等待的状态。

状态六  TIMED_WAITING(超时等待)

处于这种状态的线程不会被分配CPU执行时间,不过无需无限期待等待被其他线程显式的唤醒,在达到一定时间后它们会自动唤醒。

状态七  TERMINATED(终止状态)

线程的run()方法完成时,或者主线程的main()方法完成时,我们就认为这个线程终止了。这个线程对象也许是获得,但是它已经不是一个单独执行的线程。

线程一旦终止了,就不能复生。

在一个终止的线程上调用start()方法,会抛出java.lang.IllegalThreadStateException异常。

猜你喜欢

转载自www.cnblogs.com/0820LL/p/9667807.html