• 观测线程状态


    观测线程状态

    public class TestState {
        public static void main(String[] args) throws InterruptedException {
            Thread thread = new Thread(()->{
                for (int i = 0; i <5 ; i++) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("完成");
            });
    
            //观察状态
            Thread.State state = thread.getState();
            System.out.println(state);//New
    
            thread.start();//启动线程
            state = thread.getState();//Runnable
            System.out.println(state);
    
            while (thread.getState() != thread.getState().TERMINATED){//只要线程不结束,就一直在输出
                Thread.sleep(100);
                state = thread.getState();
                System.out.println(state);//更新线程状态
            }
        }
    }
    

    通过代码的方式观测线程的几种状态,新建运行阻塞结束

    测试线程池

    public class TestPool {
        public static void main(String[] args) {
            //1.创建服务,创建线程池
            //newFixedThreadPool 参数为:线程池大小
            ExecutorService service = Executors.newFixedThreadPool(10);
            MyThread thread = new MyThread();
            //2.执行
            service.execute(thread);
            service.execute(thread);
            service.execute(thread);
            service.execute(thread);
            //3.关闭连接
            service.shutdown();
        }
    }
    class MyThread implements Runnable{
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName());
        }
    }
    
    刚刚参加工作,很有很多不懂不会的,发现错误,欢迎指正,谢谢!
  • 相关阅读:
    网络受限下,使用Nexus要解决的两个问题
    Nexus远程Maven仓库索引下载教程
    maven--私服的搭建(Nexus的使用)
    maven命令/依赖/聚合
    mybatis常用jdbcType数据类型
    Lombok 安装、入门
    jquery append 动态添加的元素事件on 不起作用的解决方案
    Maximum Sum on Even Positions
    哈密顿
    计算几何基础
  • 原文地址:https://www.cnblogs.com/xd-study/p/13163214.html
Copyright © 2020-2023  润新知