你最好使用资源池。使用这样的东西:
public class SlowObjectPool {
private static final int POOL_SIZE = 10;
private BlockingQueue<SlowObject> slowObjectQueue = new ArrayBlockingQueue(POOL_SIZE);
public SlowObjectPool() {
for (int i = 0; i < POOL_SIZE; i++) {
slowObjectQueue.put(new SlowObject());
}
}
public SlowObject take() throws InterruptedException {
return slowObjectQueue.take();
}
public void release(SlowObject slowObject) {
// TODO You may want to log a warning if this is false
slowObjectQueue.offer(slowObject);
}
}
您可能也希望将其设为单例。然后在您的可运行文件中:
public class MyRunnable implements Runnable {
private SlowObjectPool pool;
public MyRunnable(SlowObjectPool pool) {
this.pool = pool;
}
@Override
public void run() {
// The next line blocks until a SlowObject is available
SomeObject someObject = null;
try {
someObject = pool.take()
// Do something with someObject
} catch (InterruptedException ex) {
// Thread is being ended, allow to end
} finally {
if (someObject != null)
pool.release(someObject);
}
}
}
这将在首次创建池时立即创建所有对象,而不是动态创建它们,这样您的任何可运行对象都不必等待SomeObject
创建实例。