对比单线程和多线程执行效率

@Test
    public void testThreadPool() throws InterruptedException {
        Long start = System.currentTimeMillis();
        System.out.println("普通开始时间-"+start);
        for (int i = 0; i < 1000; i++) {
//            System.out.println("普通----" + i);
            Thread.sleep(10l);
        }
        Long end = System.currentTimeMillis();
        System.out.println("普通结束时间-"+(end-start));
        ExecutorService executors = new ThreadPoolExecutor(10, 15, 0L, TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<>(1000), new ThreadPoolExecutor.CallerRunsPolicy());
        Long start1 = System.currentTimeMillis();
        System.out.println("多线程执行线程开始时间-"+System.currentTimeMillis());
        for (int ill = 0; ill < 1000; ill++) {
            final int i = ill;
            executors.execute(new Runnable() {
                @Override
                public void run() {
//                    System.out.println("执行线程----" + i);
                    try {
                        Thread.sleep(10l);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        executors.shutdown();
        while(true){
            if(executors.isTerminated()){
                Long end1 = System.currentTimeMillis();
                System.out.println("多线程执行线程结束时间-"+(end1-start1));
                System.out.println("所有的子线程都结束了!");
                break;
            }
            Thread.sleep(10);
        }
    }

  

posted on 2021-06-23 11:16  東方碩  阅读(88)  评论(0)    收藏  举报

导航