zoukankan      html  css  js  c++  java
  • 观测线程状态

    观测线程状态

    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());
        }
    }
    
    刚刚参加工作,很有很多不懂不会的,发现错误,欢迎指正,谢谢!
  • 相关阅读:
    刻意练习:从一般到卓越的方法
    Spring JMS 整合 ActiveMQ
    冒泡排序 快速排序
    TCP协议,UDP 协议的区别
    HashMap实现原理
    java 类加载过程
    Linux-vim命令(3)
    Linux-vim命令(2)
    Linux-vim命令(1)
    Linux-命令里的快捷键
  • 原文地址:https://www.cnblogs.com/xd-study/p/13163214.html
Copyright © 2011-2022 走看看