如何在Java中区分RUNNING状态与java.lang.Thread.State.RUNNABLE

前端之家收集整理的这篇文章主要介绍了如何在Java中区分RUNNING状态与java.lang.Thread.State.RUNNABLE 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

当线程是RUNNABLE时,它可以正在运行,也可以不运行.有没有办法将其与java.lang.Thread.State#RUNNABLE区别开?

Java doc中线程的所有状态:

java.lang public class Thread.State

extends Enum

A thread state. 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.

package bj.thread;

public class ThreadApp2 {

    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getState());
    }
}

输出

RUNNABLE
最佳答案
假设Thread类定义了一个函数boolean isRunning().你能用它做什么?例如,这将毫无意义:

if (t.isRunning()) {
    doXYandZ();
}

它的问题是,即使线程t实际上在isRunning()调用期间的某个时刻正在运行,也无法保证在t.isRunning()返回true时它仍将在运行.无法保证在doXYandZ()调用期间它不会停止运行.

操作系统能够区分正在运行的线程和不是由于该状态由操作系统控制的线程,并且操作系统需要记住哪些线程正在运行,哪些不是因为计划的是操作系统的工作他们.

Java运行时环境无法区分RUNNING和RUNNABLE,因为它无法控制在任何给定时间实际正在运行哪些线程,并且它无法对该状态的变化做出有意义的反应.

原文链接:https://www.f2er.com/java/532905.html

猜你在找的Java相关文章