zoukankan      html  css  js  c++  java
  • 【并发】百行代码看懂线程状态

    package club.interview.concurrent.learn;
    
    import java.util.concurrent.locks.LockSupport;
    
    /**
     * 中断 没有这个线程状态
     * {@link Thread#interrupt()}  标记为中断
     * {@link Thread#isInterrupted()} 不会清除标志位
     * {@link Thread#interrupted()}  静态方法 会清除标志位
     * thread.interrupt(); thread.isInterrupted() Thread.interrupted()
     * 阻塞  block 等锁
     *
     * @author QuCheng on 2020/6/22.
     */
    public class ThreadStatus {
    
        public static void main(String[] args) {
            Object lock = new Object();
            new Thread(() -> {
                synchronized (lock) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
            Thread thread = new Thread(() -> {
                try {
                    Thread.sleep(100);
                    LockSupport.park();
                    synchronized (lock) {
                        System.out.println("get lock");
                    }
                } catch (InterruptedException e) {
                    System.out.println("haha" + Thread.interrupted());
                }
                System.out.println("thread is finished");
            });
            System.out.println("1 " + thread.getState());
            thread.start();
            System.out.println("2 " + thread.getState());
            try {
                Thread.sleep(50);
                System.out.println("3 " + thread.getState());
                Thread.sleep(60);
                System.out.println("4 " + thread.getState());
                LockSupport.unpark(thread);
                Thread.sleep(1);
                System.out.println("5 " + thread.getState());
                System.out.println("5.1 isInterrupted = " + thread.isInterrupted());
                thread.interrupt();
                System.out.println("5.2 isInterrupted = " + thread.isInterrupted());
                System.out.println("5.3 " + thread.getState());
                thread.join();
                System.out.println("6 " + thread.getState());
            } catch (InterruptedException e) {
                System.out.println("sleep is interrupted");
            }
        }
    }

    结果

    1 NEW
    2 RUNNABLE
    3 TIMED_WAITING
    4 WAITING
    5 BLOCKED
    5.1 isInterrupted = false
    5.2 isInterrupted = true
    5.3 BLOCKED
    get lock
    thread is finished
    6 TERMINATED

     
  • 相关阅读:
    查询已存入数据库中的图片,并显示出来
    图像插值的缺点
    windows网络服务之配置网络负载均衡(NLB)群集
    QR 码的位置检测符
    二维条码识别系统设计原理
    教你看懂Code128条形码
    DataMatrix二维条码源码分析检测识别图像位置
    C#条形码生成(五)----Web下的测试
    C# 生产成条形码3种方法
    屏蔽弹出对话框
  • 原文地址:https://www.cnblogs.com/nightOfStreet/p/13384104.html
Copyright © 2011-2022 走看看