欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

executors

程序员文章站 2024-03-02 15:55:28
...

Java通过Executors框架提供四种线程池

{

        /**创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。*/
        ExecutorService executorService= Executors.newCachedThreadPool();

        for (int i=0;i<10;i++)
        {
            final int index=i;
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(index);
                }
            });

        }

    }
{
        /**创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。**/
        ExecutorService service= Executors.newFixedThreadPool(2);
        for (int i = 0; i <10 ; i++) {
            final int  index=i;
            service.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        System.out.println(index);
                        Thread.sleep(2000);
                    }catch (Exception e ){
                        System.out.println(e.getMessage());
                    }
                }
            });
        }
    }
	{


    public static void main(String[] args) {
        /**创建一个定长线程池,支持定时及周期性任务执行**/
        testOne();
        testTwo();

    }

    public static  void testOne(){
        /**表示延迟3秒执行。*/
        ScheduledExecutorService scheduledExecutorService= Executors.newScheduledThreadPool(2);
        scheduledExecutorService.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("delay 2 seconds");
            }
        },2, TimeUnit.SECONDS);
    }

    public static void testTwo(){
        /**表示延迟1秒后每3秒执行一次*/
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
        scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
            public void run() {
                System.out.println("delay 1 seconds, and excute every 3 seconds");
            }
        }, 1, 3, TimeUnit.SECONDS);
    }
}
{
        /**
         创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行**/
        ExecutorService executorService= Executors.newSingleThreadExecutor();
        for (int i = 0; i <10 ; i++) {

                final int index = i;
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(2000);
                            System.out.println(index);
                            }catch(Exception e){
                                e.getMessage();
                         }
                        }
                });

        }
    }

线程池里面做了些啥 ,JDK是有工具可以查看 jconsole 在JDK的bin目录下
executors程序在JDK中运行后的监控
executors
技术原理都差不多 多做记录 多学习