FixedThreadPool 使用方法测试

public class testFixedThreadPool{

    /**
     * 固定大小的线程池
     *
     * 同时可以处理【参数】个任务,多余的任务会排队,当处理完一个马上就会去接着处理排队中的任务。
     * Callable的任务在后面的blog有更详细的文章说明
     */
    private static void fixedThreadPool(){

        long startTime = System.currentTimeMillis();
        ExecutorService es = Executors.newFixedThreadPool(5);


        for(int i=1; i <= 15; i++){
             es.submit(new MyThread(i, es));
        }

        // 结束所有线程
//        es.shutdown();
        CreateThread createThread = new CreateThread(es);
        new Thread(createThread).start();
        System.out.println("******************************************************");
        while(true){
            try {
                Thread.sleep(500);
                System.out.println("all -- " + es.toString());
                if(es.isTerminated()){
                    System.out.println("last -- " + es.toString());
                    long end = System.currentTimeMillis();
                    System.out.println("线程执行用时: " + (end - startTime) + "ms");
                    break;
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) {
        fixedThreadPool();
    }

    static class MyThread implements Runnable
    {
        int id;
        ExecutorService exe;
        MyThread(int id, ExecutorService exe) {
            this.id = id;
            this.exe = exe;
        }
        public void run() {
            System.out.println(id + "- start");
            try {
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            /*while (true) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }*/
            System.out.println(id + "- end");
            System.out.println(id + "- exe info:" + exe.toString());
        }
    }

    static class CreateThread implements Runnable
    {
        ExecutorService exe;
        CreateThread(ExecutorService exe) {
            this.exe = exe;
        }
        public void run() {
            try {
                int n = 100;
                while (true) {
                    Thread.sleep(5000L);
                    for(int i=1; i <= 15; i++){
                        exe.submit(new MyThread(n + i, exe));
                    }
                    n++;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值