Java中线程池的使用 Java定时器Timer的使用

  在做开发时难免遇到需要多线程跑任务的场景,Java为我们提供了几种创建线程池的方法,如下图。这里不做详解,只记录一下我使用到的newCachedThreadPool()。

  废话不多说,先上代码:

  
    public void TestNvrOnline() {
        Timer timer = new Timer(true);
        //创建线程池
//        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(mapNvr.size());
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
        timer.schedule(new TimerTask() {
            public void run() {
                //你要定时执行的功能
                for (Nvr nvr : mapNvr.values()) {
                    if (nvr.getId() != null && nvr.getIp() != null) {
                        cachedThreadPool.execute(new Runnable() {
                            public void run() {
//                                Log.info(nvr.getDevicename() + "开始连接设备====" + Timestamp.valueOf(LocalDateTime.now()));
                                isHostConnectable(nvr.getId(), nvr.getIp(), nvr.getWebport(), nvr.getDevicename());
//                                Log.info(cachedThreadPool);
                            }
                        });
                    }
                }
            }
        }, 0, 3 * 60 * 1000);
    }

  代码中用到了定时器Timer,可参照我的另外一篇随笔Java定时器Timer的使用。言归正传,ExecutorService cachedThreadPool = Executors.newCachedThreadPool(),创建线程池可以使用的线程不设上线,但实际通过源码可以看到,总线程数是Integer.MAX_VALUE,即2147483647个。当然了这么多线程是足够绝大多数系统的使用了,而且这些线程是可以重复使用的。

    public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }

  需要另起一个线程时,直接cachedThreadPool.execute(Runnable command),就可以在command中执行自己要执行的代码,如果想查看线程池的使用状态,可以打印cachedThreadPool,里面有线程池中已创建和正在执行的线程概况:

    java.util.concurrent.ThreadPoolExecutor@43b2f755[Running, pool size = 15, active threads = 11, queued tasks = 0, completed tasks = 4]

  以上只是记录工作中使用的一些类库,如有不足请批评指正。

猜你喜欢

转载自www.cnblogs.com/JohanChan/p/11250932.html