Java 线程的生命周期 演示 线程的状态 附代码实现

来源:互联网 发布:如何用c语言求素数 编辑:程序博客网 时间:2024/06/14 18:17

演示线程的生命周期 

Java编程思想中如下描述:

  1. 线程状态:new、Runnable、Blocked、Dead
    1. 新建(new):当线程被创建时,它只会短暂地处于这种状态。此时它已经分配了必需的系统资源,并执行了初始化。此刻线程已经有资格获得CPU时间了,之后调度器将把这个线程转变为可运行状态或阻塞状态。(如果此时调用isAlive()方法,将返回false)
    2. 就绪(Runnable):在这种状态下,只要调度器把时间片分配给线程,线程就可运行。也就是说,在任意时刻,线程可以运行也可以不运行。只要调度器能分配时间片给线程,它就可以运行;这不同于死亡和阻塞状态。
    3. 阻塞(Blocked):线程能够运行,但有某个条件阻止它运行。当线程处于阻塞状态时,调度器将忽略线程,不会分配给线程任何CPU时间。直到线程重新进入了就绪状态,它才有可能执行操作。
    4. 死亡(Dead):处于死亡或终止状态的线程将不再是可调度的,并且再也不会得到CPU时间,它的任务已结束,或不再是可运行的。任务死亡的通常方式是从run()方法返回,但是任务的线程还可以被中断。
jdk文档中如下描述:

  1. A thread can be in one of the following states:
    • 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.


其中,BLOCKED和WAITING状态有点疑惑,在stackoverflow上找到如下描述,帮助理解:

1. The difference is relatively simple.

In the BLOCKED state, a thread is about to enter a synchronized block, but there is another thread currently running inside a synchronized block on the same object. The first thread must then wait for the second thread to exit its block.

In the WAITING state, a thread is waiting for a signal from another thread. This happens typically by calling Object.wait(), or Thread.join(). The thread will then remain in this state until another thread calls Object.notify(), or dies.



2. A thread goes to wait state once it calls wait() on an Object. This is called Waiting State. Once a thread reaches waiting state, it will need to wait till some other thread notify() or notifyAll() on the object.

Once this thread is notified, it will not be runnable. It might be that other threads are also notified(using notifyAll()) or the first thread has not finished his work, so it is still blocked till it gets its chance. This is called Blocked State.

Once other threads have left and its this thread chance, it moves to Runnable state after that it is eligible pick up work based on JVM threading mechanism and moves to run state.

附上自己的代码实现:演示线程的生命周期 欢迎讨论~

0 0
原创粉丝点击