Java线程和synchronizedlist

时间:2014-04-16 22:34:30

标签: java multithreading synchronized

我一直在学习java并试用线程并使用synchronizedlist。

package Multithreading;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
public static void main(String[] args){

    List<Integer> list = Collections.synchronizedList(new ArrayList<Integer>(10));
    for(int i=0; i<10; i++){
        list.add(0);
    }
    Thread a = new Thread(new CardPicker(list));
    Thread b = new Thread(new CardPicker(list));
    Thread c = new Thread(new CardPicker(list));
    Thread d = new Thread(new CardPicker(list));
    Thread e = new Thread(new CardPicker(list));
    Thread f = new Thread(new CardPicker(list));
    Thread g = new Thread(new CardPicker(list));
    Thread h = new Thread(new CardPicker(list));
    a.start();
    b.start();
    c.start();
    d.start();
    e.start();
    f.start();
    g.start();
    h.start();
    int startTime = (int) System.currentTimeMillis();
    while((int) System.currentTimeMillis()-startTime<10000){

    }
    System.out.println(list.toString());

}
}

package Multithreading;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class CardPicker implements Runnable{

List<Integer> list;
public CardPicker(List<Integer> list2){
    this.list = list2;
}

@Override
    public void run() {
    Random rnd = new Random();
    int hold = rnd.nextInt(10);
    while(true){
        list.set(hold, list.get(hold)+1);
    }
}

}

不知何故输出给了我类似的东西:

[13289041,13038238,0,13427372,10113077,13023511,15722188,0,12728814,0]

[12532173,0,0,12254025,12406768,16276566,12638446,16651720,0,0]

这些0来自哪里?感谢

1 个答案:

答案 0 :(得分:2)

  

这些0来自哪里?

首先,您在列表中添加了10个具有零值的项目。

在下面的行中,您将以随机索引替换该值。

Random rnd = new Random();
int hold = rnd.nextInt(10);
while(true){
    list.set(hold, list.get(hold)+1);
}

列表中有8个主题和10个值。现在,对于每个线程,仅为一次生成一个随机数,这意味着在极端情况下,为每个线程生成不同的随机数,您仍然在列表中有2个未被替换的索引。

您可以在while循环中移动到下方后再次尝试,但仍然不能100%确定所有索引都已被替换。它取决于Random的行为。

int hold = rnd.nextInt(10);

更多信息请查看Random#nextInt()