java线程池学习

来源:互联网 发布:淘宝证书安装 编辑:程序博客网 时间:2024/06/05 02:34

     通常使用 Executor(执行器) 而不是显式地创建Thread对象。ExecutorService会自动切换上下文执行线程任务。

    1.CachedThreadPool:缓存线程池,会重复利用线程,线程不够会新建。

public class ExecutorCachedThreadPool {    public static void main(String[] args)    {        ExecutorService executorService = Executors.newCachedThreadPool();        for(int i =0 ; i< 10 ; i++)        {            executorService.execute(new Runnable() {                public void run() {                    System.out.println(Thread.currentThread().getName());                }            });        }        //启动一次顺序关闭,执行以前提交的任务,但不接受新任务。        executorService.shutdown();        //如果此执行程序已关闭,则返回 true        boolean isShutdown = executorService.isShutdown();        //如果关闭后所有任务都已完成,则返回 true        boolean isTerminated = executorService.isTerminated();        while(!executorService.isTerminated())        {            Thread.yield();        }        System.out.println("main end!");    }}执行结果:pool-1-thread-2pool-1-thread-2pool-1-thread-2pool-1-thread-6pool-1-thread-4pool-1-thread-3pool-1-thread-8pool-1-thread-1pool-1-thread-5pool-1-thread-7main end!    2.FixedThreadPool:固定数量线程池,在创建时需要预先分配线程的数量,与CachedThreadPool的区别就是限制了线程的数量。
public class ExecutorFixedThreadPool {    public static void main(String[] args)    {        ExecutorService executorService = Executors.newFixedThreadPool(5);        for(int i = 0 ; i < 8 ; i ++)        {            executorService.execute(new Runnable() {                public void run() {                    System.out.println(Thread.currentThread().getName());                }            });        }        executorService.shutdown();        while(!executorService.isTerminated())        {            Thread.yield();        }        System.out.println("main end");    }}
执行结果:

pool-1-thread-2
pool-1-thread-3
pool-1-thread-4
pool-1-thread-2
pool-1-thread-2
pool-1-thread-2
pool-1-thread-1
pool-1-thread-5
main end


    3.SingleThreadPool:单线程池,一个线程执行任务,按照创建任务的顺序依次执行。

public class ExecutorSingleThread {    public static void main(String[] args)    {        ExecutorService executorService = Executors.newSingleThreadExecutor();        for(int i =0 ; i< 5 ; i++)        {            executorService.execute(new Runnable() {                public void run() {                    System.out.println(Thread.currentThread().getName());                }            });        }        executorService.shutdown();        while(!executorService.isTerminated())        {            Thread.yield();        }        System.out.println("main end");    }}
执行结果:

pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
main end


最近复习java基础,若有不妥之处欢迎指点......