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();
    }

    }

    }
  • 相关阅读:
    javascript之奇淫技巧
    nodejs的某些api~(一)node的流2
    javascript Object的新方法
    nodejs的某些api~(一)node的流1
    商城作品简介
    Javascript设计模式之观察者模式
    HTML 5 canvas globalCompositeOperation 属性
    设计模式----单利模式
    Centos6.8 安装tomcat8.5.11
    eclipse使用maven tomcat插件部署无法关联源代码
  • 原文地址:https://www.cnblogs.com/lkdirk/p/6627749.html
Copyright © 2011-2022 走看看