* 学生线程
* @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();
}
}
}