将对象从池传递到可运行的类

时间:2014-03-02 06:16:47

标签: java multithreading object-pooling

我在blockingQueue中有一个对象池。现在我想将队列中的对象分配给一个线程并在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 Object期间将对象从使用者池传递给runnable类,还是有其他方法可以做到这一点?

1 个答案:

答案 0 :(得分:2)

MrRunnable的构造函数应该获得对队列的引用