我在阻塞队列中有一个对象池。现在我想将队列中的对象分配给一个线程并在 run 方法中使用它。
最好的方法是什么?
这是我用来构建池的示例代码:
public class ConsumerPool {
private static Logger log;
//building consumer Pool
@SuppressWarnings("finally")
public BlockingQueue<OAuthConsumer> buildConsumerPool() {
BlockingQueue<OAuthConsumer> consumerObjectsQueue = null;
try {
//setting the config path
PropertyHandler.setConfigPath(propertiesMain);
String twitterPath = PropertyHandler.getProperty("twitterPath");
//setting config for twitter
PropertyHandler.setConfigPath(twitterPath);
//Blocking Linked Queue
consumerObjectsQueue = new LinkedBlockingQueue<OAuthConsumer>();
//fetching required tokens for all apps
String consumerKeySet = PropertyHandler.getProperty("consumerKey");
String consumerSecretSet = PropertyHandler.getProperty("consumerSecret");
String accessTokenSet = PropertyHandler.getProperty("accessToken");
String tokenSecretSet = PropertyHandler.getProperty("tokenSecret");
String[] splitconsumerKeys = consumerKeySet.split(",");
String[] splitconsumerSecret = consumerSecretSet.split(".");
String[] splitaccessToken = accessTokenSet.split(",");
String[] splittokenSecret = tokenSecretSet.split(".");
//creating consumer objects for each app
for (int i= 0; i< splitconsumerKeys.length; i++) {
log.info("constructing consumer object for twitter api " +i);
String consumerKey = splitconsumerKeys[i];
String consumerSecret = splitconsumerSecret[i];
String accessToken = splitaccessToken[i];
String tokenSecret = splittokenSecret[i];
OAuthConsumer consumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
consumer.setTokenWithSecret(accessToken, tokenSecret);
consumerObjectsQueue.put(consumer);
log.info("added the consumer object to que pool");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
return consumerObjectsQueue;
}
}
那是用来建立对象池的。
这是我想要创建线程的方式。
public class MrRunnable implements Runnable {
private String toFireUrl;
MrRunnable(String url){
}
@Override
public void run() {
// do some function here
}
}
public class Main {
public static void main(String[] args) {
// We will create 500 threads
for (int i = 0; i < 500; i++) {
Runnable task = new MrRunnable("some new url");
Thread worker = new Thread(task);
//start the thread
worker.start();
}
}
}
现在我想通过线程访问池中的对象。在主程序中,我应该在创建 MrRunnable 对象期间将对象从消费者池传递给可运行类,还是有其他方法可以做到这一点?