• java 线程状态


    Thread类内的State枚举描述了线程的状态:

    public enum State {
        NEW, // 线程还没有启动
        RUNNABLE, // 正在运行
        BLOCKED, // 等待监视器锁。在同步代码块外面阻塞住了
        WAITING, // 等待Object.notify(),调用Object.wait()后的状态
        TIMED_WAITING, //调用Object.wait(1000)或者Thread.sleep(1000)后的状态
        TERMINATED; //结束
    }

    代码示例打印线程状态:

    public static void main(String[] args) {
        final Object obj = new Object();
        
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized(obj) {
                    System.out.println(Thread.currentThread().getName());
                    try {
                        // TIMED_WAITING
                        // Thread.sleep(5000);
                        
                        // WAITING
                        obj.wait();
                    } catch (InterruptedException e) {}
                    
                }
            }
        });
    
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                //线程阻塞在synchronized代码块外,为blocked
                synchronized(obj) {
                    System.out.println(Thread.currentThread().getName());
                    try {
                        // TIMED_WAITING
                        obj.wait(1000);
                    } catch (InterruptedException e) {}
                    
                }
            }
        });
        
        thread.start();
        thread2.start();
        
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {}
        System.out.println(thread.getName() + "," + thread.getState());
        System.out.println(thread2.getName() + "," + thread2.getState());
    }
  • 相关阅读:
    Struts2(五)——核心拦截器
    Struts2(四)——页面相关内容
    Struts2(三)——数据在框架中的数据流转问题
    Python Day 1
    c++-STL:删除子串
    九度1165:字符串匹配
    九度1051:数字阶梯求和
    数据结构之二叉树基础三
    数据结构之二叉树基础二
    数据结构之二叉树基础一
  • 原文地址:https://www.cnblogs.com/allenwas3/p/8505945.html
Copyright © 2020-2023  润新知