线程池的复用

本文介绍了一个线程池管理类的设计与实现,包括线程池的创建、任务提交及线程工厂的具体实现。通过ThreadPoolManager类可以方便地管理线程资源,并提供了线程实例的获取方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.thread;

/**
 * 基础线程
 * @author djk
 *
 */
public abstract class BaseThread implements Runnable
{
    
    private Object o;
    
    public Object getO() {
        return o;
    }

    public void setO(Object o) {
        this.o = o;
    }

    @Override
    public void run()
    {
        run(o);
    }
    
    /**
     * 抽象的run方法
     * @param o
     */
    public abstract void run(Object o);
}

package com.thread;

import java.util.HashMap;
import java.util.Map;

/**
 * 线程工厂
 * @author djk
 *
 */
public class ThreadFactory
{
    /**
     * key放入线程的名称。value放入线程的class对象
     */
    private static Map<String,Class<?>> map  = new HashMap<String, Class<?>>(10);
    
    static
    {
        map.put("thread1",Thread1.class);
    }
    
    /**
     * 根据线程名称获得对应的线程
     * @param name
     * @return
     */
    public static BaseThread getThread(String name)
    {
        BaseThread baseThread = null;
        try {
            Class<BaseThread> claze = (Class<BaseThread>) map.get(name);
            baseThread = claze.newInstance();
        } catch (Exception e) {
        }
        
        return baseThread;
    }
    
}

package com.thread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 线程池管理
 * @author djk
 *
 */
public class ThreadPoolManager
{
    /**
     * 线程池
     */
    private ThreadPoolExecutor executor;
    
    /**
     * 任务名称
     */
    private String taskName;
    
    public ThreadPoolManager(String taskName, int corePoolSize,
            int maximumPoolSize, int queueSize)
    {
        this.taskName = taskName;
        executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, 1,
                TimeUnit.HOURS, new ArrayBlockingQueue<Runnable>(queueSize));
    }
    
    /**
     * 增加任务
     * @param o
     */
    public void addTask(Object o)
    {
        BaseThread thread =    ThreadFactory.getThread(taskName);
        if (null != thread)
        {
            thread.setO(o);
            executor.execute(thread);
        }else
        {
            System.out.println("thread is not exist....");
        }
        
    }
    
    public ThreadPoolExecutor getExecutor() {
        return executor;
    }

    public void setExecutor(ThreadPoolExecutor executor) {
        this.executor = executor;
    }
    
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值