zoukankan      html  css  js  c++  java
  • 实现个简单的线程池

    1 可以手动实现一个最简单的线程池,不考虑性能和等待机制等。
    public class Worker extends Thread {

    private LkThreadPool pool;
    private Runnable target;
    private boolean isShutDown=false;


    public Worker(Runnable target,LkThreadPool pool){
    this.pool=pool;
    this.target=target;
    }

    public synchronized void setTarget(Runnable newTarget){
    target=newTarget;
    notifyAll();
    }

    public synchronized void run(){
    while (!isShutDown){
    System.out.println(Thread.currentThread()+" 开始执行");
    if(target!=null){
    //执行
    target.run();
    }

    pool.repool(this);
    System.out.println(Thread.currentThread()+" 执行完毕 回收");
    synchronized (this){
    try {
    wait();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    }
    }

    public synchronized void shutDown(){
    isShutDown=false;

    notifyAll();
    }

    }

    public class LkThreadPool {

    private LinkedBlockingQueue<Worker> threadList ;

    private boolean isShutDown=false;

    private int threadCount=0;

    public LkThreadPool(int threadSize){
    if(threadSize>0){
    threadList= new LinkedBlockingQueue<Worker>(threadSize);
    }

    }

    //用完的线程返回线程池
    public synchronized void repool(Worker worker){
    try {
    threadList.put(worker);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }

    public synchronized void start(Runnable target){
    if(threadList.size()>0){
    //有空闲线程
    Worker worker=threadList.poll();
    worker.setTarget(target);
    }else{
    Worker worker=new Worker(target,this);
    worker.start();
    }
    }

    public synchronized void shutdown(){
    isShutDown=true;
    for(Worker worker:threadList){
    worker.shutDown();
    }

    }

    }
  • 相关阅读:
    Nacos 1.4.0 集群搭建
    docker mysql5.7
    java设计模式之简单工厂模式
    关于兑现
    Linux用户相关
    centos7开机自启动
    Shell脚本记录日志到文件
    .NetCore常用单元测试框架
    Exchange邮件开发
    Spark——Yarn模式下的日志存储及配置
  • 原文地址:https://www.cnblogs.com/lkdirk/p/6627749.html
Copyright © 2011-2022 走看看