对象池-线程池基于对象池

/**
 * 学生线程
 * @version
 */
public class StudentThread implements Runnable {


@Override
public void run() {
try {
// Thread.sleep(2000);

long id = Thread.currentThread().getId();
String threadName = Thread.currentThread().getName();
System.out.println("id:" + id +", "+ "threadName"+threadName+ ", 执行线程干一些事情...");

}catch (Exception e) {
e.printStackTrace();
}
//
synchronized(ObjectPool.studentPool) {
//对象用完后,还给对象池,重新添加进对象池
ObjectPool.studentPool.add(this);
ObjectPool.studentPool.notify();

}
}


}

----------------------------------------------------------------------------------

/**
 * 对象池
 * @version
 */
public class ObjectPool {

public static List<StudentThread> studentPool = new ArrayList<StudentThread>();

private ObjectPool() {

}

/**
* 初始化对象池, 初始化一定数量的对象

* void
*/
public static void initPool() {
synchronized(studentPool) {
if(studentPool == null) {
studentPool = new ArrayList<StudentThread>();
}
for(int i=0; i<3; i++) {
studentPool.add(new StudentThread());
}
}

}

/**
* 从池里拿出一个对象
* @return
* @throws InterruptedException
* StudentThread
*/
public static StudentThread getNextObject() throws InterruptedException {
synchronized(studentPool) {
if(studentPool.size() == 0) {
System.out.println("wait...");
studentPool.wait();
}
StudentThread object = studentPool.remove(0);
return object;
}

}

/**
* 清空 对象池
* void
*/
public static void cleanPool() {
synchronized(studentPool) {
if(studentPool != null) {
for(int i = studentPool.size()-1; i>=0; i--) {
studentPool.remove(i);
}

}
}

}

}

------------------------------------------------------------------------------------------------

/**
 * 业务类, 测试
 * @version
 */
public class TestObjectPool {


public static void main(String[] args) {

ObjectPool.initPool();

try {

StudentThread stuThread1 = ObjectPool.getNextObject();
stuThread1.run();
StudentThread stuThread2 = ObjectPool.getNextObject();
stuThread2.run();
StudentThread stuThread3 = ObjectPool.getNextObject();
stuThread3.run();

System.out.println("初始化的3个用完了后pool size:" + ObjectPool.studentPool.size());
StudentThread stuThread4 = ObjectPool.getNextObject();
stuThread4.run();

// System.out.println("清空前pool size:" + ObjectPool.studentPool.size());
// ObjectPool.cleanPool();
// System.out.println("清空后pool size:" + ObjectPool.studentPool.size());

} catch (InterruptedException e) {
e.printStackTrace();
}

}
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值