zoukankan      html  css  js  c++  java
  • Executor的线程代码

    package com.open1111;

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

    public class ExecutorTest {

        private static Integer pages=1; // 网页数
        
        private static boolean exeFlag=true; // 执行标识
        
        public static void main(String[] args) {
            ExecutorService executorService=Executors.newFixedThreadPool(10); // 创建ExecutorService 连接池默认连接10个
            
            
            while(exeFlag){
                if(pages<=100){
                    executorService.execute(new Runnable() {
                        
                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            System.out.println("爬取了第"+pages+"网页...");
                            pages++;
                        }
                    });
                }else{
                    if(((ThreadPoolExecutor)executorService).getActiveCount()==0){ // 活动线程个数是0
                        executorService.shutdown(); // 结束所有线程
                        exeFlag=false;
                        System.out.println("爬虫任务已经完成");
                    }
                }
                
                try {
                    Thread.sleep(100); // 线程休息0.1秒
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            
        }
    }

  • 相关阅读:
    NET Framework 4.5新特性 (二) 控制台支持 Unicode (UTF-16) 编码
    Openstack架构及配置
    MariaDB知识点总结03--从主+多主集群
    MariaDB知识点总结02--日志+备份
    Linux服务知识点总结
    MariaDB基本知识点总结01--介绍+语句
    Openstack知识点总结
    K8S知识点总结
    Docker知识点总结
    Zabbix介绍及安装(1)
  • 原文地址:https://www.cnblogs.com/gyadmin/p/7929439.html
Copyright © 2011-2022 走看看