简单的java线程池demo

最近看课程,简单的写了一个线程池的demo,代码如下

package com.mrhy.threaddemo.p2;

import com.sun.corba.se.spi.orbutil.threadpool.Work;
import lombok.extern.log4j.Log4j2;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

@Log4j2
public class FixedSizeThreadPool {
    //手写线程池需要准备什么?
    // 1.需要1个仓库
    private BlockingQueue<Runnable> blockingQueue;
    // 2.需要一个线程的集合
    private List<Thread> workers;


    //3. 需要具体干活的线程
    public static class Worker extends Thread {
//        图上的卡车
        // 1.到我们的仓库中去拿东西(blockingQueue)
        //

        private FixedSizeThreadPool pool;

        // 创建构造方法,声明自己属于哪个线程池
        public Worker(FixedSizeThreadPool pool) {
            this.pool = pool;
        }

        @Override
        public void run() {
//            开始工作
            while (this.pool.isWorking || this.pool.blockingQueue.size() > 0) {
                Runnable task = null;
//                从队列中拿东西的时候,需要的是阻塞
                try {
                    if (this.pool.isWorking) {
                        task = this.pool.blockingQueue.take();
                    } else {
                        task = this.pool.blockingQueue.poll();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (task != null) {
                    task.run();
                    log.info("线程:{}执行完毕", Thread.currentThread().getName());
//                    System.out.println("线程:"+Thread.currentThread().getName());
                }


            }
        }
    }

    // 线程池的初始化,构造函数
    public FixedSizeThreadPool(int poolSize, int taskSize) {
        if (poolSize <= 0 || taskSize <= 0)
            throw new IllegalArgumentException("非法参数");
        this.blockingQueue = new LinkedBlockingQueue<>(taskSize);
        this.workers = Collections.synchronizedList(new ArrayList<>());
        for (int i = 0; i < poolSize; i++) {
            Worker work = new Worker(this);
            work.start();
            workers.add(work);

        }
    }

    //    把任务提交到仓库中的办法
    public boolean submit(Runnable task) {
        if (isWorking) {
            return this.blockingQueue.offer(task);
        } else {
            return false;
        }

    }

    //    关闭的方法:
    //a.仓库停止接收任务
    //b.一旦仓库中还有任务就要继续执行
    //c. 拿任务就不该阻塞
    //d.一旦任务阻塞,我就中断他
    private volatile boolean isWorking = true;

    public void shutDown() {
//    执行关闭即可
        this.isWorking = false;
        for (Thread thread : workers) {
            if (thread.getState().equals(Thread.State.BLOCKED)) {
                thread.interrupt();// 中断线程
            }
        }
    }

    public static void main(String[] args) {
        FixedSizeThreadPool fixedSizeThreadPool = new FixedSizeThreadPool(3, 6);
        for (int i = 0; i < 6; i++) {
            fixedSizeThreadPool.submit(
                    new Runnable() {
                        @Override
                        public void run() {
                            System.out.println("放入线程");
                            try {
                                Thread.sleep(2000L);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                                log.error("一个线程被中断");
                            }
                        }
                    }
            );
        }
        fixedSizeThreadPool.shutDown();
    }

}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 前段时间遇到这样一个问题,有人问微信朋友圈的上传图片的功能怎么做才能让用户的等待时间较短,比如说一下上传9张图片,...
    加油码农阅读 4,966评论 0 2
  • 【JAVA 线程】 线程 进程:是一个正在执行中的程序。每一个进程执行都有一个执行顺序。该顺序是一个执行路径,或者...
    Rtia阅读 7,777评论 2 20
  • 前言 掌握线程池是后端程序员的基本要求,相信大家求职面试过程中,几乎都会被问到有关于线程池的问题。我在网上搜集了几...
    Jay_Wei阅读 4,571评论 0 0
  • 原文链接:http://blog.csdn.net/u010687392/article/details/4985...
    xpengb阅读 5,206评论 0 1
  • 每一件衣服, 都是一个故事。 与周先生的相识, 缘于一次偶然。当时朋友要来中山工作, 我热心的先帮她在她要工...
    妙手量衣阅读 3,051评论 0 0

友情链接更多精彩内容