Java开发

线程池

2020-02-09  本文已影响0人  风中小酌

线程池的应用场景:

使用线程池执行大量的 Runnable 命令

public class TestPool1 {
    public static void main(String[] args) {
        //创建线程池
        //1、线程池中只有一个线程对象
        //      ExecutorService exe = Executors.newSingleThreadExecutor();
        //2、线程池中有固定数量的线程对象
        ExecutorService exe = Executors.newFixedThreadPool(10);
        //3、线程池中线程数量动态变化
        //      ExecutorService exe = Executors.newCachedThreadPool();
    
        /** 使用线程执行大量的 Runnable 命令*/
        for(int i=0;i<20;i++){
            final int n = i; //防止在同一线程中变量被修改
        
            //任务
            //使用匿名内部类
            Runnable command = new Runnable() {
            
                @Override
                public void run() {
                    System.out.println("开始执行: " + Thread.currentThread().getName() + n);
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                
                    System.out.println("执行结束: " + n);
                }
            }; //任务结束
            //将任务交给线程池中的线程去执行
            exe.execute(command);
        }
    
        //关闭线程池
        exe.shutdown();
    }
}

使用线程池执行大量的 Callable 任务

public class TestPool2 {
    public static void main(String[] args) {
        //创建线程池
        //1、线程池中只有一个线程对象
        //      ExecutorService exe = Executors.newSingleThreadExecutor();
        //2、线程池中有固定数量的线程对象
        //      ExecutorService exe = Executors.newFixedThreadPool(10);
        //3、线程池中线程数量动态变化
        ExecutorService exe = Executors.newCachedThreadPool();
        //使用集合存储Future对象
        List<Future> list = new ArrayList<Future>();
        /** 使用线程执行大量的 Callable 任务*/
        for(int i=0;i<20;i++){
            //任务
            //使用匿名内部类
            Callable<Integer> task = new Callable<Integer>() {

                @Override
                public Integer call() throws Exception {
                    Thread.sleep(2000);
                    return (int) (Math.random() * 10) + 1;
                }
            }; //任务结束
            //将任务交给线程池
            Future ft = exe.submit(task);
            //将Future对象添加到集合中
            list.add(ft);
        }
    
        //循环输出Future结果
        for(Future f : list){
            try {
                System.out.println(f.get());
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ExecutionException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        //关闭线程池
        exe.shutdown();
    }
}
上一篇 下一篇

猜你喜欢

热点阅读