观测线程状态

观测线程状态

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());
    }
}
posted @ 2020-06-19 15:13  小徐学狂  阅读(136)  评论(0编辑  收藏  举报