本文由Scarb发表于金甲虫的博客,转载请注明出处

线程的状态转换以及基本操作^线程的状态转换以及基本操作

线程基本操作:sleep yield join

  • sleep:当前线程暂停一段时间,让给别的线程运行

    Causes the currently executing thread to sleep (temporarily cease
    execution) for the specified number of milliseconds

  • yield:让出一下CPU,从CPU暂时退出一下

    A hint to the scheduler that the current thread is willing to yield
    its current use of a processor. The scheduler is free to ignore this
    hint.

  • join:在thread1运行中调用thread2.join(),此时停止thread1,运行thead2直至结束,再回到thread1运行。

    Waits for this thread to die.

  • interrupt:打断线程,线程被打断后会抛出一个InterruptedException

    Interrupts this thread.

线程状态^Life Cycle of a Thread in Java

线程生命周期

  • NEW:new Thread()

    Thread state for a thread which has not yet started.

  • RUNNABLE:new Thread().start() 被线程调度器执行

    Thread state for a runnable thread. A thread in the runnable
    is executing in the Java virtual machine but it may
    waiting for other resources from the operating system
    as processor.

    • Ready:在CPU等待队列中等待,Thread.yield(),线程被挂起
    • Running:线程被调度器选中执行,在CPU中运行
  • TERMINATED:线程终止,不可再运行

    Thread state for a terminated thread.
    The thread has completed execution.

  • TIMED_WAITING:按时长等待

    Thread state for a waiting thread with a specified waiting time.

  • WAITING:等待

    Thread state for a waiting thread.

  • BLOCKED:等待进入同步代码块的锁

    Thread state for a thread blocked waiting for a monitor lock.