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());
        }
    }
    
    刚刚参加工作,很有很多不懂不会的,发现错误,欢迎指正,谢谢!
  • 相关阅读:
    java基础 Collections.sort的两种用法
    Mysql常用命令详解
    2、Java并发编程:如何创建线程
    JAR、WAR、EAR的使用和区别
    区分Oracle的数据库,实例,服务名,SID
    Mysql 启动运行
    3、Java并发编程:Thread类的使用
    1、Java多线程基础:进程和线程之由来
    文件上传利器SWFUpload使用指南
    网络矩阵
  • 原文地址:https://www.cnblogs.com/xd-study/p/13163214.html
Copyright © 2011-2022 走看看