2016-08-23 22 views
0

我有一个品牌列表,我想为每个对象设置品牌特定的属性并运行它的一个线程。MultiThreading - 使用相同的属性创建线程而不是正确的循环

但是,当我运行下面的代码...它创建了同一品牌的多个线程,并留下了几个品牌。

brightCoveVideoInfoPullerThread是一个可运行的类。在这个对象中,我通过BrightCoveAPIParam添加了品牌特定的属性。

for (int i = 0; i < brands.size(); i++) { 
    String brand = brands.get(i); 
    brightCoveVideoInfoPullerThread.setBrightCoveAPIParam(properties.get(brand)); 
    Thread t = new Thread(brightCoveVideoInfoPullerThread, 
    "BrightCovePullerThreadFor" + brand); 
    t.start(); 
} 

Brightcove的轮询的HEALTHCOM

Brightcove的轮询的HEALTHCOM

Brightcove的轮询的FOODANDWINE

Brightcove的轮询的FOODANDWINE

+3

看起来你需要在每次循环创建'brightCoveVideoInfoPullerThread'的新实例。 –

回答

1

要重复使用相同的实例brightCoveVideoInfoPullerThread循环的每一次迭代。使用setter更改该实例的属性将更新所有线程的属性,因为所有线程都运行同一个实例。

环内创建它的一个新的实例,使每个线程都有自己的实例:

for (String brand : brands) { 
    BrightCoveVideoInfoPullerThread brightCoveVideoInfoPullerThread = new ...; 
    brightCoveVideoInfoPullerThread.setBrightCoveAPIParam(properties.get(brand)); 

    Thread t = new Thread(brightCoveVideoInfoPullerThread, "BrightCovePullerThreadFor" + brand); 
    t.start(); 
} 
相关问题