• 【并发】百行代码看懂线程状态


    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

     
  • 相关阅读:
    C#路径中获取文件全路径、目录、扩展名、文件名称
    c#FTP应用---windows iis
    c#FTP应用---FileZilla Server
    在VS2010中使用Git管理源代码
    ABB机器人---PCSDK简介
    几款软件需求分析工具
    快速排序
    springmvc和struts2的区别比较
    Struts中ActionContext和ServletActionContext的比较
    设计模式--适配器模式
  • 原文地址:https://www.cnblogs.com/nightOfStreet/p/13384104.html
Copyright © 2020-2023  润新知