Java线程池的实现

在实现线程池之前,要先了解几个跟线程池有关的概念。线程,任务,任务池和线程池。

线程在Wiki上的意思是是"进程"中某个单一顺序的控制流,指运行中的程序的调度单位。这个我觉得理解有些难,不如把它理解成流水线。一个线程看成一个流水线,它处理完一个任务(原料)就给关了,也可以一直处理任务(原料)。那么任务就可以理解成流水线的原料,任务池可以理解为原料仓库,池程池可以理解为工厂。

我们的线程池的功能就和工厂差不多,当要加工的原料特别多时,如果有之前闲置的流水线,需要打开他就行,如果打开了还不行,那得再买几条(新建线程)。如果原料特别少,我们可能选择关闭几条流水线(暂停线程处理),甚至可以卖掉几条流水线(停止关闭线程)。

如果只是要实现基本的线程池的话,Java已经提供了一个:java.util.concurrent.Executors。如果想自己实现的话,我下面提供了一个简单的实现例子。

任务代码:

Java
package net.yutuo.thread;

public abstract class ThreadTask implements Runnable {
    protected String name;

    public ThreadTask(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

线程代码:

Java
package net.yutuo.thread;

import java.util.Date;

public abstract class ThreadWork extends Thread {
    private Date startTime;

    protected boolean isShutDown;

    public abstract ThreadTask getTask();

    public void shutdown() {
        this.isShutDown = true;
        System.out.println(getName() + " is set to shut down.");
    }

    public Date getStartTime() {
        return this.startTime;
    }

    public long getConstTime() {
        if (startTime == null) {
            return 0;
        }
        return new Date().getTime() - startTime.getTime();
    }

    @Override
    public void run() {
        System.out.println(getName() + " is starting.");

        while (!isShutDown) {
            ThreadTask task = getTask();
            if (task == null) {
                try {
                    sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                continue;
            }

            System.out.println(getName() + " seted a task[" + task.getName() + "].");

            this.startTime = new Date();
            try {
                task.run();
            } catch (Throwable e) {
                e.printStackTrace();
            }
            this.startTime = null;
        }

        System.out.println(getName() + " is shut down.");
    }
}

线程池代码:

Java
package net.yutuo.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

public class ThreadPool {
    private String threadName;
    private int maxCount;
    private Queue<ThreadTask> queue;
    private List<ThreadWork> works;

    public ThreadPool(String threadName, int maxCount) {
        this.threadName = threadName;
        this.maxCount = maxCount;
        this.queue = new ConcurrentLinkedQueue<ThreadTask>();
        this.works = new ArrayList<ThreadWork>();
    }

    public void showdown() {
        for (ThreadWork work : works) {
            work.shutdown();
        }

        System.out.println("Thread pool is show downed.");
    }

    public synchronized void addTask(ThreadTask task) {
        queue.offer(task);
    }

    private synchronized ThreadTask getTask() {
        return queue.poll();
    }

    public void start() {
        for (int i = 0; i < maxCount; i++) {
            ThreadWork work = new PoolWork();
            work.setName(threadName + "-" + (i + 1));
            works.add(work);
            work.start();
        }
    }

    class PoolWork extends ThreadWork {
        @Override
        public ThreadTask getTask() {
            return ThreadPool.this.getTask();
        }
    }
}

测试代码:

Java
package net.yutuo.thread;

public class Test {

    public static void main(String[] args) {

        ThreadPool pool = new ThreadPool("ThreadMW", 4);

        System.out.println("Thread pool is starting.");

        pool.start();

        for (int i = 0; i < 100; i++) {
            ThreadTask task = new TestTask("task-" + (i + 1));
            pool.addTask(task);
        }

        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        pool.showdown();

        System.out.println("Program end");

    }

    static class TestTask extends ThreadTask {
        public TestTask(String name) {
            super(name);
        }

        @Override
        public void run() {

            System.out.println("[" + Thread.currentThread().getName() + "]" + name + " is started");

            for (int i = 0; i < 1000000000; i++) {
                Math.log(i);
            }

            System.out.println("[" + Thread.currentThread().getName() + "]" + name + " is ended");
        }
    }
}

转载请注明:宇托的狗窝 » Java线程池的实现

发表我的评论
取消评论

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址