对象池模式

来源:互联网 发布:java项目发布到服务器 编辑:程序博客网 时间:2024/06/04 01:03

对象池是使用成员变量来存储生成的对象


1、我需要一个放入池中的对象

public class Teacher {    @Override    public String toString() {                return "我是一个老师";    }}

2、我需要池中对象的状态

public class ObjectStatus {    private boolean status = true;    /**     * 占用     */    public void use() {        status = false;    }    /**     * 释放     */    public void release() {        status = true;    }    /**     * 检查是否可用     *     * @return     */    public boolean check() {        return status;    }}


3、构造一个对象池

public class TeacherPool {    private volatile ConcurrentHashMap<Teacher, ObjectStatus> pool = new ConcurrentHashMap<>();    /**     * 初始化对象池     */    public TeacherPool() {        pool.put(new Teacher(), new ObjectStatus());    }    /**     * 取出可用对象     *     * @return     */    public synchronized Teacher take() {        for (Teacher t : pool.keySet()) {            if (pool.get(t).check()) {                pool.get(t).use();                return t;            }        }        Teacher t = new Teacher();        pool.put(t, new ObjectStatus());        return t;    }    /**     * 归还已用对象     *     * @param t     */    public synchronized void put(Teacher t) {        pool.get(t).release();    }    /**     * 当前对象池大小     *     * @return     */    public synchronized int size() {        return pool.size();    }}

4、输出看效果

public class TeacherPoolExample {    public static void main(String[] args) {        TeacherPool pool = new TeacherPool();        new Thread(() -> {            Teacher teacher = pool.take();            System.out.println(teacher.toString() + pool.size());            pool.put(teacher);        }).start();        try {            Thread.sleep(2000);        } catch (InterruptedException e) {            e.printStackTrace();        }        new Thread(() -> {            Teacher teacher = pool.take();            System.out.println(teacher.toString() + pool.size());            pool.put(teacher);        }).start();            }}

我是一个老师1
我是一个老师1

原创粉丝点击