MultiThreading - 使用相同的属性创建线程,而不是正确的循环

时间:2016-08-23 10:52:37

标签: java 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();
}

e.g

HEALTHCOM的Brightcove Poller

HEALTHCOM的Brightcove Poller

Brightcove Poller for FOODANDWINE

Brightcove Poller for FOODANDWINE

1 个答案:

答案 0 :(得分:1)

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

在循环内创建一个新实例,以便每个线程都有自己的实例:

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

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