首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java多线程的实现(创建一个线程池并且简单的使用)

java多线程的实现(创建一个线程池并且简单的使用)

作者头像
gfu
发布2019-08-28 14:44:16
2.8K0
发布2019-08-28 14:44:16
举报
文章被收录于专栏:gfugfu

什么时候用多线程?

image.png

程序执行结果:

image.png

先说一下此处的打印,第一个参数是当前线程名称,由于线程之间是异步执行,有的还没创建好,有的后来居上就执行完了,打印线程的名称会这样,第二个参数是优先级,默认都是5,第三个参数是线程组名称。

github地址:https://github.com/furtech/java_utils/blob/master/src/main/java/com/furtech/javautils/ThreadPool.java

package com.furtech.javautils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.LinkedBlockingQueue;

/**
 * @des 线程池的简单实现(可扩展)
 *
 * @author 719383495@qq.com | 719383495qq@gmail.com | 有问题可以邮箱或者github联系我
 * @date 2019/8/4 13:55
 */
public class ThreadPool {
    /**@des logger */
    private static final Logger logger = LoggerFactory.getLogger(ThreadPool.class);
    private final int poolSize;
    private final LinkedBlockingQueue queue;
    private final PoolWorker[] runable;

    public ThreadPool(int poolSize) {
        this.poolSize = poolSize;
        queue = new LinkedBlockingQueue();
        runable = new PoolWorker[poolSize];
        for (int i = 0; i < poolSize; i++) {
            runable[i] = new PoolWorker();
            new Thread(runable[i], "pool-" + i).start();
        }
    }

    public void execute(Runnable task) {
        synchronized (queue) {
            queue.add(task);
            queue.notify();
        }
    }

    private class PoolWorker implements Runnable {
        @Override
        public void run() {
            Runnable task ;

            while (true) {
                synchronized (queue) {
                    while (queue.isEmpty()) {
                        try {
                            queue.wait();
                        } catch (Exception e) {
                            logger.info("exception in queue waiting :{}",e.getMessage());
                        }
                    }
                    task = (Runnable) queue.poll();
                }
                try {
                    task.run();
                } catch (RuntimeException e) {
                    logger.info("run exception : {}", e.getMessage());
                }

            }
        }
    }

}

class ThreadPoolMain {
    public static void main(String[] args) {
        ThreadPool pool = new ThreadPool(5);
        int MaxSize = 100;
        for (int i = 0; i < MaxSize; i++) {
            pool.execute(() -> System.out.println(Thread.currentThread()));
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019.08.04 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档