线程创建和销毁会消耗很多的资源,当我们创建线程时,会发现cpu利用率很高,为了节省资源的使用,使用线程池是一个比较好的选择,当有任务需要执行时,随机分配给一条线程去执行,也可以删除任务,获取任务数量等。下面使用springboot构建一个简单的线程池。

自定义线程池

package com.demo.bootdemo.threadpool;

import java.util.LinkedList;
import java.util.List;

public class MyThreadPool {
    // 线程用于执行任务,所以要具有执行任务,添加线程,减少线程,获取任务数量,释放线程,定时执行任务等操作
    private LinkedList<Thread> threadPool = new LinkedList<Thread>();
    // 存放需要执行的任务
    private LinkedList<Job> jobs = new LinkedList<Job>();
    // 线程池容量
    private int capacity;

    public MyThreadPool() {
        capacity = 10;
        init();
    }

    public MyThreadPool(int capacity) {
        this.capacity = capacity;
        init();
    }

    /**
     * 初始化
     */
    private void init() {
        for (int i = 0; i < capacity; i++) {
            Thread th = new Thread(new MyRunnable(), "th_" + i);
            threadPool.add(th);
            th.start();
        }
    }

    /**
     * 执行单个任务
     * 
     * @param job
     */
    public void executeJob(Job job) {
        addJob(job);
    }

    /**
     * 批量执行任务
     * 
     * @param jobList
     */
    public void executeJobs(List<Job> jobList) {
        addJobs(jobList);
    }

    public void deleteJob(String jobKey) {
        synchronized (jobs) {
            Job delJob = null;
            for (Job j : jobs) {
                if (jobKey.equals(j.getJobKey())) {
                    delJob = j;
                    break;
                }
            }
            // 删除
            jobs.remove(delJob);
        }
    }

    private void addJobs(List<Job> jobList) {
        synchronized (jobs) {
            if (jobList != null && jobList.size() > 0) {
                jobs.addAll(jobList);
                jobs.notifyAll();
            }
        }
    }

    private void addJob(Job job) {
        synchronized (jobs) {
            jobs.add(job);
            jobs.notify();
        }
    }

    /**
     * 获取任务数量
     * 
     * @return
     */
    public int getJobSize() {
        return jobs.size();
    }

    private class MyRunnable implements Runnable {
        public void run() {
            // 任务列表中没有任务,则等待,否则取出任务执行
            while (true) {
                Job job = null;
                synchronized (jobs) {
                    if (jobs.isEmpty()) {
                        try {
                            jobs.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        job = jobs.removeFirst();
                    }
                }
                if (job != null) {
                    job.execute();
                }
            }
        }
    }
}
View Code

相关文章:

  • 2022-12-23
  • 2021-10-18
  • 2021-08-09
  • 2022-01-08
  • 2021-07-28
  • 2021-12-26
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-02-16
  • 2021-06-21
  • 2022-12-23
  • 2021-05-25
  • 2021-08-12
  • 2022-12-23
  • 2022-01-16
相关资源
相似解决方案