(黑马Java多线程与并发库高级应用)09 Java5线程并发库的应用

 线程池

package cn.itcast.heima2;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolTest {

    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 10; i++) {
            final int task_index = i;
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i < 10; i++) {
                        try {
                            Thread.sleep(20);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        System.out.println(Thread.currentThread().getName() + " is loopping of " + i + " for task of "
                                + task_index);
                    }
                }
            });
        }
        
        threadPool.shutdown();
    }

}

结果就是指有三个线程在跑,没有多余的线程

 

动态线程池

package cn.itcast.heima2;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolTest {

    public static void main(String[] args) {
//        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        
        ExecutorService threadPool = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            final int task_index = i;
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i < 10; i++) {
                        try {
                            Thread.sleep(20);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        System.out.println(Thread.currentThread().getName() + " is loopping of " + i + " for task of "
                                + task_index);
                    }
                }
            });
        }
        
        threadPool.shutdown();
    }

}

 

posted @ 2017-07-24 16:35  z_dominic  阅读(163)  评论(0编辑  收藏  举报