编程语言
首页 > 编程语言> > 如何在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,因为它无法控制在任何给定时间实际正在运行哪些线程,并且它无法对该状态的变化做出有意义的反应.

标签:multithreading,java
来源: https://codeday.me/bug/20191210/2105241.html