执行后将线程状态保存到打印列表

时间:2014-11-10 17:16:15

标签: java list concurrency threadpool

我是网络抓取工具的新手,我正在尝试抓取一个网站(这是成功的)并将我想要的数据添加到同步列表中,这是成功的。但是,在执行线程池之后,如何打印该数据列表。

我的思绪已经空白但基本上如果我有一个超类汽车和子类porshe,ferrari等,并且子类实现了runnable,并且在成功抓取之后,数据被添加到超类列表中。如何检查此列表仅用于调试目的,以便我事先知道我可以将数据保存到数据库。

修改

这是我的主要方法

public static void main(String[] args) {
    System.out.println("thread pool started");
    ExecutorService exec = Executors.newFixedThreadPool(2);
    for (int i=0; i<1; i++){  
        exec.execute(new Porshe());
        exec.execute(new Ferrari());
    }
    exec.shutdown();
    try {
        exec.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
    } catch (InterruptedException ex) {
        Logger.getLogger(JSoupTest.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.out.println("Thread pool exited, printing list");
}

我需要在此处打印添加到同步列表中的所有汽车的列表

这是超类

public class Cars {

public List<JSONObject> list;
private int count = 1;

public Cars(){
    list = Collections.synchronizedList(new ArrayList<JSONObject>());
}
public synchronized void addToMap(JSONObject obj){
        list.add(obj);
};
...etc

这是实现runnable的子类,因此可以作为线程执行

public class Porshe extends Cars implements Runnable{

private String url = "";
private JSONObject data = new JSONObject();

public Porshe() {
    super();
    this.url = "http://www.autotrader.co.uk"
}
   @Override
public void run() {
    crawl(20);
}

1 个答案:

答案 0 :(得分:0)

您使列表同步。如果多个线程同时访问列表,这将非常有用。这可能是您的意图:所有汽车都会爬网,并将其结果同时添加到单个列表中。但这不是你所做的:每个Car实例都有自己的列表,与其他汽车共享,因此可以从一个线程访问。

您应该创建一个单独的同步列表,并将此列表作为参数传递给您的汽车的构造函数。因此,每辆车都会将其结果添加到同一个唯一列表中。完成后,列表为空:

List<JSONObject> resultList = Collections.synchronizedList(new ArrayList<JSONObject>());
System.out.println("thread pool started");
ExecutorService exec = Executors.newFixedThreadPool(2);
for (int i=0; i<1; i++){  
    exec.execute(new Porshe(resultList));
    exec.execute(new Ferrari(resultList));
}
exec.shutdown();

...

System.out.println("And the result is: " + resultList);
相关问题