JAVA-Thread 线程的几种状态

Oracle JDK 定义中,线程一共有六种状态

https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.State.html

NEW:未启动状态

Thread t = new Thread() {
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
};
System.out.println(t.getState().name());

RUNNABLE:可运行状态

处于可运行状态的线程正在 Java 虚拟机中执行,但也可能是正在等待来自操作系统资源,例如 CPU。

Thread t = new Thread() {
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
};
t.start();
System.out.println(t.getState().name());

BLOCKED:阻塞状态

final Object lock = new Object();

Thread t = new Thread() {
    @Override
    public void run() {
        synchronized (lock) {
            System.out.println(Thread.currentThread().getName());
        }
    }
};

synchronized (lock) {
    try {
        t.start();
        Thread.sleep(1000);
        System.out.println(t.getState().name());
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

WAITING:等待状态

调用以下方法,使线程处于等待状态:

Object.wait()、Thread.join()、LockSupport.park()

另一个线程调用以下方法,使线程继续执行:

Object.notify()、 Object.notifyAll()、Thread.join()
final Object lock = new Object();

Thread t = new Thread() {
    @Override
    public void run() {
        try {
            synchronized (lock) {
                lock.wait();
                System.out.println(Thread.currentThread().getName());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
};
t.start();

try {
    Thread.sleep(1000);
} catch (InterruptedException e) {
    e.printStackTrace();
}

synchronized (lock) {
    System.out.println(t.getState().name());
    lock.notifyAll();
}

TIMED_WAITING:具有指定时间的等待状态

调用以下方法,使线程处于指定时间的等待状态:

Thread.sleep()、Object.wait()、Thread.join()、LockSupport.parkNanos()、LockSupport.parkUntil()
Thread t = new Thread() {
    @Override
    public void run() {
        try {
            Thread.sleep(2000);
            System.out.println(Thread.currentThread().getName());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
};
t.start();

try {
    Thread.sleep(1000);
} catch (InterruptedException e) {
    e.printStackTrace();
}
System.out.println(t.getState().name());

TERMINATED:已终止线程的线程状态或线程已完成执行

Thread t = new Thread() {
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
};
t.start();

try {
    Thread.sleep(1000);
} catch (InterruptedException e) {
    e.printStackTrace();
}
System.out.println(t.getState().name());

线程的状态图


https://blog.csdn.net/pange1991/article/details/53860651

猜你喜欢

转载自www.cnblogs.com/jhxxb/p/10821483.html