zoukankan      html  css  js  c++  java
  • Thread

    Thread几种状态

    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()

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

    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());
  • 相关阅读:
    1144 The Missing Number (20分)
    1145 Hashing
    1146 Topological Order (25分)
    1147 Heaps (30分)
    1148 Werewolf
    1149 Dangerous Goods Packaging (25分)
    TypeReference
    Supervisor安装与配置()二
    谷粒商城ES调用(十九)
    Found interface org.elasticsearch.common.bytes.BytesReference, but class was expected
  • 原文地址:https://www.cnblogs.com/LQBlog/p/15268773.html
Copyright © 2011-2022 走看看