栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java 多线程 线程池

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java 多线程 线程池

1.创建一个线程池的类

public class ZimeitiPool {
    private static ThreadPoolExecutor pool = null; //线程池

    private static BlockingQueue workQueue = null; //阻塞队列

    private static int corePoolSize = 5; //核心线程数

    private static int maxinumPoolSize = 10;//最大线程数

    private static long keepAliveTime = 10 * 1000l;//生存时间

    private final static AtomicInteger threadsNumber = new AtomicInteger(1);

    private static int workQueueSize = 100; //阻塞队列容量

    public static ThreadPoolExecutor getPool() {
        if (pool == null) {
            workQueue = new linkedBlockingQueue(workQueueSize);

            pool = new ThreadPoolExecutor(corePoolSize, maxinumPoolSize, keepAliveTime, TimeUnit.MILLISECONDS,
                    workQueue);

            pool.setThreadFactory(new ThreadFactory() {

                @Override
                public Thread newThread(Runnable r) {
                    Thread t = new Thread(r, "zimeiti-pool-" + threadsNumber.getAndIncrement());
                    return t;
                }
            });
        }
        return pool;
    }
}

2.写自己的业务逻辑代码,需要实现Runnable或者继承Thread,如需返回值则实现callable

public class JiemianhaoInfo implements Runnable{
    private Logger log = LoggerFactory.getLogger(JiemianhaoInfo.class);

    String url;
    int id;

    public JiemianhaoInfo(String url,int id) {
        this.url=url;
        this.id=id;
    }



    @Override
    public void run() {

        try {
            fetch();
        } catch (Exception e) {
            
        }

    }

    public void fetch() {

       // 业务代码

    }
}

3.让线程去执行业务代码

public class ZimeitiInfo {
    public static void main(String[] args) throws IOException {
        Log4jConfiguration.load("conf/log4j.xml");
        Context.getApplicationContext();

        String preUrl = "https://a.jiemian.com/index.php?m=user&a=centerArticle&id=";
        for (int i=100000000;i<120000000;i++){
            String url = preUrl+i;
            try{
                ZimeitiPool.getPool().execute(new JiemianhaoInfo(url,i));
            }catch (final RejectedExecutionException e) {
                try {
                    i = i-1;
                    System.out.println("线程队列满了,sleep 5s . current queue size:"
                            + ZimeitiPool.getPool().getQueue().size() + ",active:"
                            + ZimeitiPool.getPool().getActiveCount());
                    Thread.sleep(5000);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
            }catch (Exception e){
                i = i-1;
                e.printStackTrace();
            }

        }

    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/683936.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号